Find substring

https://loj.ac/problem/103

Title Description

  Given a string A and string B , B seeking the A number of occurrences of. A and B in English characters are uppercase or lowercase letters.

Thinking

  Obviously, this is my path string matching problem, we can solve with KMP. But here I mainly want to introduce a more simple way: the string Hash. We went to a base b, seen as a string of hexadecimal number b. In order to obtain Hash value of the string length as soon as possible, we can use the scroll Hash. This process can be completed using recursion: H (C, K +. 1) H = (C, K) + B * C K +. 1 . Thus we can find the Hash value calculated from the string length n k starts from the following equation:

                H (C ') = H (C, k + n) -H (C, k) * b n .

  Then do it again on the line.

Code

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull b=131;
char s1[1000005],s2[1000005];
ull power[1000005],sum[1000005]; 
int main() 
{
    scanf(" %s %s",s1+1,s2+1);
    power[0]=1;
    for(int i=1;i<1000000;i++)
        power[i]=power[i-1]*b;
    int m=strlen(s1+1),n=strlen(s2+1);
    for(int i=1;i<=m;i++)
        sum[i]=sum[i-1]*b+s1[i];
    ull s=0,ans=0;
    for(int i=1;i<=n;i++)
        s=s*b+s2[i];
    for(int i=0;i<=m-n;i++)
        if(s==sum[i+n]-sum[i]*power[n])ans++;
    printf("%lld",ans);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/fangbozhen/p/11618425.html