您的位置:首页 > 其它

【小算法】KMP字符串匹配算法实现

2013-08-28 18:02 447 查看
只贴代码,具体的思想百度百科中有。

#include <stdio.h>
#include <string.h>

void getNext(const char *str, int *next)
{
int i = 0;
int j = -1;
int len = strlen(str);

next[0] = -1;

while(i < len - 1)
{
if(j == -1 || str[i] == str[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}

}

int KMP_match(const char *mainStr, const char *subStr)
{
int mLen = strlen(mainStr);
int sLen = strlen(subStr);
int i = 0;
int j = 0;
int *pNext = NULL;

pNext = (int *)malloc(sLen*sizeof(int));
getNext(subStr, pNext);

while (i < mLen && j < sLen)
{
if (j == -1 || mainStr[i] == subStr[j])
{
i++;
j++;
}
else
{
j = pNext[j];
}
}

free(pNext);

if (j == sLen)
{
return (i - j + 1);
}

return -1;
}

int main()
{
char *str1 = "afasdfasdfjowerpopnmvhn;asf";
char *str2 = "pop";

printf("match = %d\n", KMP_match(str1, str2));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: