题目链接
题目描述
解题思路
字符串匹配问题使用kmp算法
代码实现
class Solution {
public:
vector<int> getNextArray(string s) {
int n = s.size();
vector<int> next(n, 0);
int j = 0;
for (int i = 1; i < n; ) {
if (s[i] == s[j]) {
next[i] = j + 1;
++i;
++j;
} else {
if (j != 0) {
j = next[j - 1];
} else {
next[i] = 0;
++i;
}
}
}
return next;
}
vector<int> KMP(string s, string p) {
vector<int> next = getNextArray(p);
int n = s.size();
int m = p.size();
vector<int> match;
for (int i = 0, j = 0; i < n; ) {
if (s[i] == p[j]) {
++i;
++j;
} else {
if (j != 0) {
j = next[j - 1];
} else {
++i;
}
}
if (j == m) {
match.push_back(i - m);
j = next[j - 1];
}
}
return match;
}
vector<int> beautifulIndices(string s, string a, string b, int k) {
vector<int> indicesA = KMP(s, a);
vector<int> indicesB = KMP(s, b);
vector<int> result;
for (int i : indicesA) {
for (int j : indicesB) {
if (abs(i - j) <= k) {
result.push_back(i);
break;
}
}
}
return result;
}
};
总结
熟练掌握kmp算法模板