KMP算法是一种更高效的字符串匹配算法,关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。
(1)朴素查找算法
代码如下:
int BF(const char *str,const char *sub,int pos)//朴素查找算法Index//O(n*m)
{
int lens = strlen(str);
int lensub = strlen(sub);
if(pos<0 || pos>=lens)
{
return -1;
}
int i = pos;
int j = 0;
while(i<lens && j<lensub)
{
if(str[i] == sub[j])
{
i++;
j++;
}
else
{
i = i-j+1;
j = 0;
}
}
if(j >= lensub)
return i - j;
else
return -1;
}
(2)KMP算法
代码如下:
static int * GetNext(const char *sub)
{
int len = strlen(sub);
assert(len >= 2);
int *next = (int *)malloc(len*sizeof(int));
next[0] = -1;
next[1] = 0;
int j = 1;
int k = 0;
while(j+1 < len)
{
if((k==-1) || (sub[k]==sub[j]))
next[++j] = ++k;
else
k = next[k];
}
return next;
}
int KMP(const char *str,const char *sub,int pos)//O(n+m)
{
int lens = strlen(str);
int lensub = strlen(sub);
if(pos<0 || pos>=lens)
return -1;
int i = pos;
int j = 0;
int *next = GetNext(sub);
while(i<lens && j<lensub)
{
if((j==-1) || (str[i]==sub[j]))
{
i++;
j++;
}
else
j = next[j];
}
free(next);
if(j >= lensub)
return i-j;
else
return -1;
}