您的位置:首页 > 其它

Kmp算法

2014-04-08 20:30 274 查看
/*
时间复杂度O(a.length() + b.length())
最小覆盖字串(len - next[len - 1] - 1)
单串模式匹配
*/

void get_next(char* s)
{
next[0] = -1;

for (int i = 1, j = -1; i < strlen(s); i++)
{
while (j >= 0 && s[i] != s[j + 1])
{
j = next[j];
}

if (s[i] == s[j + 1])
{
j++;
}

next[i] = j;
}
}

int kmp(char* a, char* b)
{
int res = 0, len = strlen(b);
get_next(b);

for (int i = 0, j = -1; i < strlen(a); i++)
{
while (j >= 0 && a[i] != b[j + 1])
{
j = next[j];
}

if (a[i] == b[j + 1])
{
j++;
}

if (j == len - 1)
{
res++;
j = next[j];	//计算有多少个
}
}

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