kmp 在n中找m

#include
#include
#include
#include
using namespace std;
int nextn[1005];
string m, n;
void getnext()
{
int len;
len = m.length();
int a, b;
a = 0;
b = -1;
nextn[0] = -1;//别忘了初始化
while (a < len)
{
if (b == -1 || m[a] == m[b])
{
nextn[++a] = ++b;
}
else
{
b = nextn[b];
//b = nextn[a];别这样错了!!!!!!!
}
}
}


int kmp()
{
int len1 = n.length();
int len2 = m.length();
int a, b;
a = b = 0;
while (a < len1&&b < len2)
{
if (b == -1 || n[a] == m[b])
{
b++;
a++;
}
else
{
b = nextn[b];
}
}
if (b == len2)
{
return a - b + 1;//返回坐标;
}
else
{
return -1;
}
}
int main()
{
cin >> m >> n;//在n里面找m;
getnext();
cout< return 0;
}

你可能感兴趣的:(kmp 在n中找m)