#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct
{
char data[20];
int length;
}SqString;
void GetNext(SqString t, int next[])
{
int j, k;
j = 0;
k = -1; next[0] = -1;
while (j < t.length - 1)
{
if (k == -1 || t.data[j] == t.data[k])
{
j++; k++;
next[j] = k;
}
else k = next[k]; //k回退
}
}
int KMPIndex(SqString s,SqString t)
{
int next[20];
int i = 0, j = 0;
GetNext(t,next);
while (i < s.length && j < t.length)
{
if (j == -1 || s.data[i] == t.data[j])
{
i++;
j++; //i、j各增1
}
else j = next[j]; //i不变,j后退
}
if (j >= t.length)
return(i - t.length); //返回匹配模式串的首字符
else
return(-1); //返回不匹配标志
}
void StrAssign(SqString& s, char cstr[],int len)
{
int i;
for ( i = 0; i< len; i++)
s.data[i] = cstr[i];
s.length = i;
}
void DispStr(SqString s)
{
int i;
if (s.length > 0)
{
for (i = 0; i < s.length; i++)
cout << s.data[i] << endl;
}
}
int main()
{
SqString pre;
SqString fors;
int nextpre[10];
char prechar[] = { 'a','b','c','d','s','s' };
char forschar[] = { 'c','d','s' };
StrAssign(pre, prechar, sizeof(prechar) / sizeof(prechar[0]));
StrAssign(fors, forschar, sizeof(forschar) / sizeof(forschar[0]));
DispStr(pre);
cout << endl;
DispStr(fors);
cout << KMPIndex(pre, fors);
system("pause");
}
C++KMP算法的调试源代码
最新推荐文章于 2023-05-13 11:23:16 发布