#include <vector>
#include <iostream>
#include <string>
using namespace std;
void getNext(string& pattern, vector<int>& next) {
int n = pattern.length();
next.resize(n);
next[0] = -1;
int j = -1;
for (int i = 1; i < n; i++) {
while (j != -1 && pattern[i] != pattern[j + 1]) {
j = next[j];
}
if (pattern[i] == pattern[j + 1]) {
j++;
}
next[i] = j;
}
}
bool KMP(string& text, string& pattern) {
int m = text.length(), n = pattern.length();
vector<int>next(n);
getNext(pattern, next);
//for (auto x : next)cout << x << " ";
//cout << endl;
int j = -1;
for (int i = 0; i < m; i++) {
while (j != -1 && text[i] != pattern[j + 1]) {
j = next[j];
}
if (text[i] == pattern[j + 1]) {
j++;
}
if (j + 1 == n)return true;
}
return false;
}
int main() {
string text = "", pattern = "";
while (cin >> text >> pattern) {
auto ans = KMP(text, pattern);
if (ans)cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
KMP算法
最新推荐文章于 2023-01-23 18:57:44 发布