您的位置:首页 > 其它

字符串匹配——KMP算法

2015-04-14 21:44 274 查看
#include <cstdio>
#include <cstring>

const int N = 1000000 + 5;
char s
,t
;
int lens,lent;

int next
;

void get_fail() {
next[0] = -1;
for (int i = 1,j = -1; i < lent; ++ i) {
while (j != -1 && t[i] != t[j+1]) j = next[j];
next[i] = t[i] == t[j+1] ? ++ j : j ;
}
}

int work() {
lens = strlen(s);
lent = strlen(t);
get_fail();
int ret = 0;
for (int i = 0,j = -1; i < lens; ++ i) {
while (j != -1 && s[i] != t[j+1]) j = next[j];
if (s[i] == t[j+1]) {
++ j;
if (j == lent-1) {
j = -1;
ret ++;
}
}
}
return ret;
}

int main() {
// freopen ("a.txt" , "r" , stdin ) ;
while (scanf("%s",s) != EOF) {
scanf("%s",t);
printf("%d\n",work());
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: