kmp單片自動機

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;

int nxt[maxn];
// find s in t
int kmp(char *s, char *t) {
    int ret = 0;
    int m = strlen(s);
    nxt[0] = -1;
    for (int i = 1, j = -1; i < m; i++) {
        while (j != -1 && s[i] != s[j + 1]) {
            j = nxt[j];
        }
        if (s[i] == s[j + 1]) {
            j++;
        }
        nxt[i] = j;
    }
//  for(int i = 1 ; i < m; i ++){
//      cout <<" i =  "<<i <<" next  = "<< nxt[i] <<endl;
//  }
    int n = strlen(t);
    for (int i = 0, j = -1; i < n; i++) {
        while (j != -1 && t[i] != s[j + 1]) {
            j = nxt[j];
        }
        if (t[i] == s[j + 1]) {
            j++;
        }
        if (j == m - 1) {
            ret++;
            j = nxt[j];
        }
    }
    return ret ; 
}

int main(){
    char t[100] ="accbaccbaccaccbbbaccaccd" ;
    char s[100] ="accaccd";
    cout << t <<endl;
    cout << kmp(s, t) << endl;


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章