输入t,表示t趟;然后主串、模式串,以此类推。
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
class Mystring
{
public:
Mystring();
~Mystring();
void Setval(string sp);
int KMPFindsubstr(string p, int pos);
private:
string mainstr;
int size;
void GetNext(string p, int next[]);
int KMPFind(string p, int pos, int next[]);
};
void Mystring::GetNext(string p, int next[])
{
next[0] = -1;
int i = 0, j = -1;
int len = p.length();
while (i < len)
{
if (j == -1 || p[i] == p[j])
{
i++;
j++;
next[i] = j;
/* 以下为nextval:
if(p[i] == p[j])
next[i] = next[j];
else
next[i] = j;
*/
}
else
{
j = next[j];
}
}
}
int Mystring::KMPFind(string p, int pos, int next[])
{
int i, j;
for (i = 0, j = 0; i < mainstr.size() && j < (int)p.size();)
{
if (j == -1 || mainstr[i] == p[j])
i++, j++;
else
j = next[j];
}
if (j == p.size())
return i - j + 1;
return 0;
}
Mystring::Mystring()
{
size = 0;
mainstr = "";
}
Mystring::~Mystring()
{
size = 0;
mainstr = "";
}
void Mystring::Setval(string sp)
{
mainstr = "";
mainstr.assign(sp);
size = mainstr.length();
}
int Mystring::KMPFindsubstr(string p, int pos)
{
int i;
int L = p.length();
int* next = new int[L+1];
GetNext(p, next);
for (i = 0; i < L; i++)
{
cout << next[i] << ' ';
}
cout << endl;
int v = -1;
v = KMPFind(p, pos, next);
delete[]next;
return v;
}
int main()
{
int t;
cin >> t;
while (t--)
{
Mystring str;
string mainstr, substr;
cin >> mainstr >> substr;
str.Setval(mainstr);
int ans;
ans=str.KMPFindsubstr(substr, 0);
cout << ans << endl;
}
return 0;
}