杭电1686——KMP(字符串匹配)
原题传送门
KMP裸题,感觉最近开始水题目数量了。
炒鸡!炒鸡!炒鸡!!!详细的KMP讲解。视频链接
# include <iostream>
# include <algorithm>
# include <string>
# include <cstdio>
# include <cstring>
using namespace std;
const int maxn = 1e5;
int g[maxn] = { 0 };//g[i]:前i个字符的最大公共前后缀的长度
void gt(string s) {//传入字符串s,更新g数组
int len = s.size();
int i = 0, j = 1;
while (j < len) {
if (s[i] == s[j]) {
g[j] = i + 1;
i++;
j++;
}
else {
if (i == 0) {
g[j] = 0;
j++;
continue;
}
i = g[i - 1];
}
}
}
int kmp(string s,string t) {//传入子串s,父串t,返回s在t中出现的次数
gt(s);
int i = 0, j = 0;
int sum = 0;
int ls = s.size();
int lt = t.size();
while (i <= lt) {
if (t[i] == s[j]) {
i++;
j++;
if (j == ls) {
sum++;
j = g[j - 1];
}
}
else {
if (j == 0) {
i++;
continue;
}
j = g[j - 1];
}
}
return sum;
}
int main() {
ios::sync_with_stdio(false);
int T;
cin >> T;
while (T--) {
string s, t;
cin >> s;
cin >> t;
cout << kmp(s, t) << endl;;
}
return 0;
}