#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define maxn 1000
using namespace std;
void getnext(char t[], int next[]){
memset(next, 0, sizeof(next));
int j = 0, k = -1;
int len = strlen(t);
next[0] = -1;
while(j < len) {
if(k == -1 || t[j] == t[k]) {
j++, k++;
if(t[j] != t[k]) {
next[j] = next[k];
}
else{
next[j] = k;
}
}
else{
k = next[k];
}
}
}
int kmp(char *s, char *t) {
int next[maxn];
int slen = strlen(s);
int tlen = strlen(t);
int i = 0, j = 0, v;
getnext(t, next);
while(i < slen && j < tlen) {
if(j == -1 || s[i] == t[j]) {
i++, j++;
}
else {
j = next[j];
}
}
if(j >= tlen) {
v = i - tlen;
}
else {
v = -1;
}
return v;
}
int main() {
char s1[maxn], t1[maxn];
gets(s1);
gets(t1);
int res = kmp(s1, t1);
cout << res << endl;
return 0;
}
//感悟:用不同的方式实现一个算法,真正理解她!
KMP算法
最新推荐文章于 2014-04-07 21:20:46 发布