KMP求匹配字符串位置
//获取模式串p的next数组
void GetNext(char *p, int *next)
{
int length = strlen(p);
int left = -1;
int right = 0;
next[0] = -1;
while(right<length-1)
{
if((left == -1)||(p[left]==p[right]))
{
left++; //匹配:左右指针同时后移,next[right]赋值为左指针地址(匹配地址)
right++;
next[right]=left;
}
else
{
left=next[left]; //不匹配:右指针不动,左指针按照已完成的next数组向左寻找
}
}
}
//寻找匹配字符串的位置
int KmpSearch(char *s, char *p)
{
int sLength = strlen(s);
int pLength = strlen(p);
int *next = new int[pLength+1];
GetNext(p, next);
int sPointer = 0;
int pPointer = 0;
while((sPointer<sLength)&&(pPointer<pLength))
{
if((pPointer==-1)||(s[sPointer]==p[pPointer]))
{
sPointer++;
pPointer++;
}
else //不匹配,模式串指针按照next数组向左移动
{
pPointer=next[pPointer];
}
}
delete []next;
if(pPointer == pLength)
return sPointer-pLength;
else
return -1;
}
void main()
{
char *s = "abcdefghijklmnhijkl";
char *p = "hij";
int pos = KmpSearch(s,p);
cout<<pos<<endl;
}