您的位置:首页 > 其它

字符串匹配-KMP算法

2014-05-21 21:40 351 查看
每次看KMP算法都要像看新知识点一样,故用通俗的语言记录此算法。

KMP算法是保存前缀数组next而达到匹配过程中不回溯指针,提高时间效率的目的。

先举例,

i指针记录主串下标; j指针记录模式串下标

   i=2 3 4 5 6

a b a b c a b c a b c a c b a b

      a b c a c

   j=0 1 2 3 4

S[6]!=T[4], 由于T[0]=T[3],且为abca这个串的相等前缀和后缀的最大长度(即ab!=ca),故下趟比较为下图

a b a b c a b c a b c a c b a b

               a b(从此处开始比较即可)

该算法的关键在于如何求取next数组?

        next[j]=k:代表T[0].....T[k-1]=T[j-k]……T[j-1],

                      表明当模式中T[j]与主串中相应字符不相等时,T[next[j]]重新与主串中字符进行匹配

int* getNext(char *needle)

{
int len=strlen(needle);
int i=0;
int *next=new int[len];
next[0]=-1;
int k=-1;
while(i<len)
{
if( k==-1 || needle[k]==needle[i])
{
++k;
++i;
next[i]=k;
}
else
{
k=next[k];//此处可以理解为不匹配时,则模式串回到next[k]的位置重新比较
}
}
return next;

}

匹配函数

int strStr(char *haystack,char *needle)

{
   int lenOfHaystack=strlen(haystack);
int lenOfNeedle=strlen(needle);
int *next=new int[lenOfNeedle];
next=getNext(needle);
if(lenOfHaystack<lenOfNeedle)
return 0;
if(lenOfHaystack==0)
return 0;
if(lenOfNeedle==0)
return 0;
int res=-1;
int h=0;
int n=0;
while(h<lenOfHaystack && n<lenOfNeedle)
{
if(n==-1 || haystack[h] == needle
)
{
if(res == -1)
{
res=h;
}
++h;
++n;
}
else
{
n=next
;
res=-1;
}
}

if(n>=lenOfNeedle)
{
return res;
}
else
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: