您的位置:首页 > 编程语言 > C语言/C++

KMP算法C++实现

2014-06-06 20:13 246 查看
#include <iostream>
#include <cstring>

using namespace std;

int *getNext(const char *T,int len)
{
int i = 0;
int j = -1;
int *next = new int[len];
next[0] = -1;
while(i < len - 1)
{
if(j == -1 || T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}

int KMP(const char *S,const char *T)
{
int i = 0;
int j = 0;
int lens = strlen(S);
int lent = strlen(T);
int *next = getNext(T,lent);
while(i < lens && j < lent)
{
if(j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
delete[] next;
if(j == lent)
return i - lent;
return -1;
}

int main()
{
char S[100],T[100];
cin >> S >> T;
cout << KMP(S,T) + 1 << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp c++ 算法