KMP算法问题
程序如下:
#include <string.h>
#include <stdlib.h>
#include<string.h>
#define MAXSIZE 20
void GetNext(const char *T,int *next)//求next数组
{
int i = 0,j = -1;
int T_len;
T_len = strlen(T);//模式串的长度
next[0] = -1;
while(i < T_len-1)
{
if(j == -1 || T[i] == T[j])
{
++i;
++j;
if(T[i] != T[j])
next[i] = j;
else
next[i] = next[j];
}
else
next[j] = j;
}
}
int Index_KMP(char *S,char *T,int pos)
{
int next[MAXSIZE];
GetNext(T,next);
int i = pos;//从pos开始匹配
int j = 0;
int S_len,T_len;
S_len = strlen(S);//目标串长度
T_len = strlen(T);//模式串的长度
while(i < S_len && j < T_len)
{
if(j == -1 || S[i] == T[j])
{
++i;
++j;
}
else
j = next[j];
}
if(j == T_len)
return i-T_len;
else
return -1;
}
void main()
{
char patt[MAXSIZE];
char des[1024];
puts("请输入模式串:");
gets(patt);
puts("请输入目标串:");
gets(des);
int pos = Index_KMP(des,patt,0);
printf("模式串在目标串的第%d个位置\n",pos);
}
当模式串的长度<=2时,程序能很好的运行,但当模式串的长度>=3时,就好像陷入了死循环一样,CPU使用率达100% 。
请高人指教