AcWing 776. 字符串移位包含问题
原题链接
困难
KMP算法解决字符串匹配问题
#include<iostream>
using namespace std;
int nextn[100];
void get_next(string t){
int m = t.size();
for(int i = 1; i < m; i ++){
int j = nextn[i];
while(j > 0 and t[i] != t[j]){
j = nextn[j];
}
if(t[i] == t[j])
nextn[i + 1] = j + 1;
else
nextn[i + 1] = 0;
}
}
int get_anwser(string s, string t){
int ans = 0, j = 0;
int m = s.size();
int n = t.size();
for(int i = 0; i < m; i ++){
while(j > 0 and s[i] != t[j])
j = nextn[j];
if(s[i] == t[j])
j += 1;
if(j == n){
ans += 1;
j = nextn[j];
}
}
return ans;
}
int main(){
string s, t;
cin >> s >> t;
if((int)s.size() < (int)t.size()) swap(s, t);
s += s;
get_next(t);
if(get_anwser(s, t))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
}