Hash 匹配字符串模板

板子:

void init(char *s) { //预处理主串的Hash前缀hash值和p的次方.
    p[0] = 1;
    Hash[0] = 0;
    int k =strlen(s+1);
    for(int i=1;i<=k;i++) p[i] = p[i-1] * base;
    for(int i=1;i<=k;i++) Hash[i] = Hash[i-1] * base + (s[i] - 'A' + 1);
}
ull get(int l,int r) { //由公式得到hash[r-l]的值.
    return Hash[r] - Hash[l-1] * p[r-l+1];
}

模板题

const int maxn=1e6+5;
const int mod = 1e9+7;
const ull base = 233;
ull Hash[maxn], p[maxn];
char s1[10005];  //子串
char s2[maxn];   //主串

void init(char *s) { //预处理主串的Hash前缀hash值和p的次方.
    p[0] = 1; Hash[0] = 0;
    int k = strlen(s+1);
    for(int i = 1 ; i <= k ; i ++) p[i] = p[i-1] * base;
    for(int i = 1 ; i <= k ; i ++) Hash[i] = Hash[i-1] * base + (s[i] - 'A' + 1);
}
ull get(int l,int r) { //由公式得到hash[r-l]的值.
    return Hash[r] - Hash[l-1] * p[r-l+1];
}
void solve() {
    scanf("%s",s1);
    scanf("%s",s2+1);
    int len1 = strlen(s1);
    int len2 = strlen(s2+1);
    init(s2);   //预处理子串.
    ull haha = 0;
    int res = 0;
    for(int i = 0 ; i < len1 ; i ++) haha = haha * base + (s1[i] - 'A' + 1);
    for(int i = 1 ; i+len1-1 <= len2 ; i ++) {
        ull hs = get(i, i+len1-1);  //每次访问len1个长度.
        if(hs == haha)
            res++;
    }
    printf("%d\n", res);
}

Hash的灵活运用
//容易搞错的点就是在求Hash[r,l]的值, 注意下标和区间长度. 总之要把公
//式记的牢,并且在写序号是最好举个例子写一写,才不容易错.
AC Code

#define ull unsigned long long int
const int maxn= 5e6+5;
const ull mod = 1e9+7;
const ull base = 13;
ull Hash[maxn];
ull p[maxn];   //它会一直取mod, 保证它的范围在[0,2^64-1], 是负数也会自己取mod.
char s1[maxn];
char s2[maxn];
char tmp[maxn];
void init() {
    p[0] = 1;
    for(int i=1;i<=maxn;i++) p[i] = p[i-1] * base;
    //for(int i=1;i<=k;i++) Hash[i] = Hash[i-1] * base + (s[i] - 'A' + 1);
}

ull get(int l,int r) {
    return Hash[r] - Hash[l-1]*p[r-l+1];
}

void solve() {
    init();
    while(~scanf("%s",s1)){
        scanf("%s",s2);
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        if(len1 > len2){
            printf("%s\n",s2);
            continue;
        }
        ull haha = 0;
        Fill(tmp,0); int top = 0;
        for(int i=0;i<len1;i++) haha = haha * base + (s1[i] - 'a' + 1);
        Hash[0] = 0;
        for(int i=0;i<len2;i++){
            tmp[top++] = s2[i];   //此时用Hash数组去代表tmp的此时的前缀和.
            Hash[top] = Hash[top-1] * base + (s2[i] - 'a' + 1 );
            if(top >= len1 && get(top-len1+1,top) == haha){
                top -= len1;
            }
        }
        for(int i=0;i<top;i++){
            printf("%c",tmp[i]);
        }
        printf("\n");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值