KMP模板

作者: 四川孙一峰 | 来源:发表于2017-04-11 17:03 被阅读0次
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<queue>
#include<vector>
#include<cmath>
#define LL long long
#define eps 1e-6
#define CLR(x) memset(x,0,sizeof(x))
using namespace std;
const int maxn = 100;

int next[1000];
char str1[1000];
char str2[1000];

void getnext(char s2[]){
    int t1 = 0;
    int t2 = -1;
    next[0] = -1;
    int len2 = strlen(s2);
    while(t1 < len2){
        if(t2 == -1 || s2[t1] == s2[t2]){
            t1++;
            t2++;
            next[t1] = t2;
        }
    }
}

int kmp(char s1[] , char s2[]){
    int t1 = 0 , t2 = 0;
    int con = 0;
    int len1 = strlen(s1) , len2 = strlen(s2);
    while(t1 < len1){
        if(t2 == -1 || s1[t1] == s2[t2] ){
            t1++;
            t2++;
        }
        else t2 = next[t2];

        if(t2 == len2){
            con++;
            t2 = next[t2];
        }
    }
    return con;
}

int main(){
    cin >> str1 >> str2;
    getnext(str2);
    int ans = kmp(str1,str2);
    cout << ans << endl;
}

相关文章

网友评论

      本文标题:KMP模板

      本文链接:https://www.haomeiwen.com/subject/vijuattx.html