KMP的典型应用,就是个模板题
值得注意的是,这个题是不区分大小写的,最开始写了一直不对,开始怀疑是不是背错模板了,最后重新读了一遍题才发现不区分大小写,所以说,深刻的教训
认真读题!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#include<bits/stdc++.h>
#include<unordered_map>
#define int int64_t
using namespace std;
int n, m,nxt[1000];
string s1, s2;
void getNext() {
int pre = 0, i = 1;
while (i < s1.size()) {
if (s1[i] == s1[pre]) {
pre++;
nxt[i++] = pre;
}
else {
if (pre) pre = nxt[pre - 1];
else i++;
}
}
}
void solve() {
int cnt = 0;
cin >> n >> m >> s1 >> s2;
for (int i = 0; i < n; ++i) s1[i] = tolower(s1[i]);
for (int i = 0; i < m; ++i) s2[i] = tolower(s2[i]);
memset(nxt, 0, sizeof nxt);
getNext();
int i = 0, j = 0;
while (i < s2.size()) {
if (s1[j] == s2[i])i++, j++;
else {
if (j) j = nxt[j - 1];
else i++;
}
if (j == s1.size()) {
cnt++;
j = nxt[j - 1];
}
}
cout << cnt << endl;
}
signed main() {
ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
int t; cin >> t;
while (t--) {
solve();
}
return 0;
}