您的位置:首页 > 其它

KMP算法的简明实现

2011-03-23 14:10 369 查看

kmp算法简明实现

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char t[10], s[20];
cin>>s>>t;
int next[11], d = strlen(t), k = strlen(s);
int i = 0, j = -1, l = 0;
next[0] = -1;
while(i < d)
{
if(j == -1 || t[i] == t[j])
{
i++;j++;
next[i] = j;
}
else
j = next[j];
}
for(int w=0; w < d; w++) //显示各next值
cout<<next[w]<<endl;
i = 0;
j = 0;
while(i < k && j < d)
if(j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
j = next[j];
if(j == d)
l = i - d;

if(l) cout<<l<<endl;
else cout<<"fail"<<endl;
return 0;
}本文出自 “璨夏爱程序” 博客,转载请与作者联系!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: