KMP

#include<bits/stdc++.h>
#define ri register int
#define ll long long
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
const inline int read(){
    int k = 0, f = 1; char c = getchar();
    for(;!isdigit(c); c = getchar())
        if(c == '-') f = -1;
    for(;isdigit(c); c = getchar())
        k = k * 10 + c - '0';
    return k * f;
}
#define maxn 1000005
int next[maxn];
char s1[maxn], s2[maxn];
void get_next(char *s){
    int len = strlen(s);
    int i = 0, j = -1;
    next[0] = -1;
    while(i < len){
        while(j != -1 && s[i] != s[j])
            j = next[j];
        next[++i] = ++j;
    }
}
int kmp(char *s, char *p){
    int lens = strlen(s), lenp = strlen(p);//一定要预处理出长度 
    int ans = 0;
    int i = 0, j = 0;
    while(i < lens){
        while(j != -1 && s[i] != p[j])
            j = next[j];
        ++i;
        ++j;
        if(j == lenp){
            ans++;
            j = next[j];
        }
    }
    return ans;
}
int main(){
    fast;
    cin >> s1 >> s2;
    get_next(s2);
    cout << kmp(s1, s2);
//    int lenp = strlen(s2);
//    for(ri i = 1; i <= lenp; ++i)
//        cout << next[i] << " ";
    return 0;
}

https://www.cnblogs.com/zssst/p/11806898.html

posted @ 2020-03-29 13:14  kojoker  阅读(111)  评论(0)    收藏  举报