3008. 找出数组中的美丽下标 II - 力扣(LeetCode)
class Solution {
public:
vector<int> kmp(string s1, string s2) {
int n = s1.size(), m = s2.size();
vector<int> v(m, -1), ret;
int i = 0, j = -1;
while (i < m - 1) {
if (j == -1 || s2[i] == s2[j]) v[++i] = ++j;
else j = v[j];
}
i = j = 0;
while (i < n) {
if (j == -1 || s1[i] == s2[j]) i++, j++;
else j = v[j];
if (j == m) {
ret.push_back(i - j);
i--;
j = v[j - 1];
}
}
return ret;
}
vector<int> beautifulIndices(string s, string a, string b, int k) {
auto bb = kmp(s, b), aa = kmp(s, a);
vector<int> ans;
int pos = 0;
for (int x : aa) {
while (pos < bb.size() && x - k > bb[pos]) pos++;
if (pos < bb.size() && bb[pos] <= x + k) {
ans.push_back(x);
}
}
return ans;
}
};