|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<int> beautifulIndices(string s, string patternA, string patternB, int k) { |
| 4 | + vector<int> beautifulIndicesA = kmpSearch(s, patternA); |
| 5 | + vector<int> beautifulIndicesB = kmpSearch(s, patternB); |
| 6 | + |
| 7 | + sort(beautifulIndicesB.begin(), beautifulIndicesB.end()); |
| 8 | + |
| 9 | + vector<int> result; |
| 10 | + for (int indexA : beautifulIndicesA) { |
| 11 | + int left = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA - k) - beautifulIndicesB.begin(); |
| 12 | + int right = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA + k + patternB.length()) - beautifulIndicesB.begin(); |
| 13 | + |
| 14 | + left = (left >= 0) ? left : -(left + 1); |
| 15 | + right = (right >= 0) ? right : -(right + 1); |
| 16 | + |
| 17 | + for (int indexB = left; indexB < right; indexB++) { |
| 18 | + if (abs(beautifulIndicesB[indexB] - indexA) <= k) { |
| 19 | + result.push_back(indexA); |
| 20 | + break; |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + return result; |
| 26 | + } |
| 27 | + |
| 28 | +private: |
| 29 | + vector<int> kmpSearch(string text, string pattern) { |
| 30 | + vector<int> indices; |
| 31 | + vector<int> pi = computePrefixFunction(pattern); |
| 32 | + |
| 33 | + int q = 0; |
| 34 | + for (int i = 0; i < text.length(); i++) { |
| 35 | + while (q > 0 && pattern[q] != text[i]) { |
| 36 | + q = pi[q - 1]; |
| 37 | + } |
| 38 | + if (pattern[q] == text[i]) { |
| 39 | + q++; |
| 40 | + } |
| 41 | + if (q == pattern.length()) { |
| 42 | + indices.push_back(i - q + 1); |
| 43 | + q = pi[q - 1]; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return indices; |
| 48 | + } |
| 49 | + |
| 50 | + vector<int> computePrefixFunction(string pattern) { |
| 51 | + int m = pattern.length(); |
| 52 | + vector<int> pi(m, 0); |
| 53 | + int k = 0; |
| 54 | + for (int q = 1; q < m; q++) { |
| 55 | + while (k > 0 && pattern[k] != pattern[q]) { |
| 56 | + k = pi[k - 1]; |
| 57 | + } |
| 58 | + if (pattern[k] == pattern[q]) { |
| 59 | + k++; |
| 60 | + } |
| 61 | + pi[q] = k; |
| 62 | + } |
| 63 | + return pi; |
| 64 | + } |
| 65 | +}; |
0 commit comments