#include<iostream>
using namespace std;
#include<string>
const int N = 100010;
int Next[N];
void get_next(string t)
{
int j = 1, k = 0;
Next[1] = 0;
while (j < t.length())
{
if (k == 0 || t[j - 1] == t[k - 1])
{
Next[++j] = ++k;
}
else
k = Next[k];
}
}
int kmp(string s, string t, int pos)
{
int n = s.length(), m = t.length();
int i = pos;
int j = 1;
while (i <= n && j <= m)
{
if (j == 0 || s[i - 1] == t[j - 1]) i++, j++;
else j = Next[j];
}
if (j > m) return i - m;
else return -1;
}
int main()
{
string src, tar;
getline(cin, src); getline(cin, tar);
if (src.length() < tar.length())
swap(src, tar);
get_next(tar);
if (kmp(src, tar, 1) != -1)
cout << tar << " is substring of" << src << endl;
else cout << "no substring" << endl;
return 0;
}
KMP核心算法
最新推荐文章于 2024-08-29 16:37:54 发布