您的位置:首页 > 其它

KMP算法实现

2015-11-11 13:10 295 查看
#include<iostream>
#include<string.h>
using namespace std;

void GetNext(char *p,int next[]);
int  KmpMatch(char *s,char *p,int next[]);

int main()
{
char *p = new char;
char *s = new char;
cin.getline(s,100);
cin.getline(p,100);

int temp[100];
// Next函数值计算
GetNext(p,temp);
// KMP匹配执行
cout<<KmpMatch(s,p,temp)<<endl;
return 0;
}

void GetNext(char *p,int temp[])
{
int pLen = strlen(p);

int i = 0;
int j = -1;

temp[0] = -1;
while(i < pLen-1)
{
if (j == -1 || p[i] == p[j])
{
i++;
j++;
if (p[i] != p[j])
{
temp[i] = j;
}
else
{
temp[i] = temp[j];
}
}
else
{
j = temp[j];
}
}
}

int  KmpMatch(char *s,char *p,int temp[])
{
int sLen = strlen(s);
int pLen = strlen(p);

int i = 0;
int j = 0;

while (i < sLen && j < pLen)
{
if (j== -1 || s[i] == p[j])
{
i++;
j++;
}
else
{
j = temp[j];
}
}

if (j == pLen)
{
return i-j;
}
else {
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编码