一定要注意,string::size()和string::length()方法返回的不是int类型,条件判断的时候最好转一下,不然有时候就会出现意想不到的问题。(这个搞了我一下午。。。。)
#include<iostream>
#include<string>
using namespace std;
const int M = 1005;
int ne[M];
int m, n;
string s, t;
void get_next()
{
int i = 0, j = -1;
ne[0] = -1;
while (i < m )
{
if (j == -1 || t[j] == t[i])
{
++i;
++j;
ne[i] = j;
}
else
j = ne[j];
}
}
void kmp()
{
int i = 0, j = 0,ans=0;
get_next();
while (i < n)
{
if (j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
j = ne[j];
if (j >= int(t.size()))//改成t.size()死循环
{
cout << "t.size():"<<t.size() << endl;
cout <<"m:" <<m << endl;
ans++;
j = 0;
}
}
cout << ans << endl;
}
int main()
{
while (1)
{
cin >> s;
if (s == "#")
break;
cin >> t;
m = t.size();
n = s.size();
kmp();
}
return 0;
}