比如主串为:”1001110110”
子串为:”11“
则出现位置分别为:3 4 7
//KMP算法 2015.6.7
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char *s = "1001110110";
char *p = "11";
int ar[20] = { 0 };
//next
ar[0] =-1;
int i = 0,l=-1;
while (i < strlen(p)-1) //next函数
{
if (l==-1||p[i] == p[l])
{
i++; l++;
ar[i] = l;
}
else
l = ar[l];
}
int m=0, n=0;
while (m < strlen(s)) //根据next判断是否匹配
{
if (n==-1||s[m] == p[n])
{
m++; n++;
}
else n = ar[n];
if (n == strlen(p))
{
cout << m - strlen(p) << endl;
n == 0;
m -= strlen(p)-1;
}
}
system("pause");
return 0;
}