|
57 | 57 |
|
58 | 58 | ## 解法
|
59 | 59 |
|
| 60 | +```cpp |
| 61 | +class Solution { |
| 62 | +public: |
| 63 | + vector<int> beautifulIndices(string s, string patternA, string patternB, int k) { |
| 64 | + vector<int> beautifulIndicesA = kmpSearch(s, patternA); |
| 65 | + vector<int> beautifulIndicesB = kmpSearch(s, patternB); |
| 66 | + |
| 67 | + sort(beautifulIndicesB.begin(), beautifulIndicesB.end()); |
| 68 | + |
| 69 | + vector<int> result; |
| 70 | + for (int indexA : beautifulIndicesA) { |
| 71 | + int left = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA - k) - beautifulIndicesB.begin(); |
| 72 | + int right = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA + k + patternB.length()) - beautifulIndicesB.begin(); |
| 73 | + |
| 74 | + left = (left >= 0) ? left : -(left + 1); |
| 75 | + right = (right >= 0) ? right : -(right + 1); |
| 76 | + |
| 77 | + for (int indexB = left; indexB < right; indexB++) { |
| 78 | + if (abs(beautifulIndicesB[indexB] - indexA) <= k) { |
| 79 | + result.push_back(indexA); |
| 80 | + break; |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return result; |
| 86 | + } |
| 87 | + |
| 88 | +private: |
| 89 | + vector<int> kmpSearch(string text, string pattern) { |
| 90 | + vector<int> indices; |
| 91 | + vector<int> pi = computePrefixFunction(pattern); |
| 92 | + |
| 93 | + int q = 0; |
| 94 | + for (int i = 0; i < text.length(); i++) { |
| 95 | + while (q > 0 && pattern[q] != text[i]) { |
| 96 | + q = pi[q - 1]; |
| 97 | + } |
| 98 | + if (pattern[q] == text[i]) { |
| 99 | + q++; |
| 100 | + } |
| 101 | + if (q == pattern.length()) { |
| 102 | + indices.push_back(i - q + 1); |
| 103 | + q = pi[q - 1]; |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + return indices; |
| 108 | + } |
| 109 | + |
| 110 | + vector<int> computePrefixFunction(string pattern) { |
| 111 | + int m = pattern.length(); |
| 112 | + vector<int> pi(m, 0); |
| 113 | + int k = 0; |
| 114 | + for (int q = 1; q < m; q++) { |
| 115 | + while (k > 0 && pattern[k] != pattern[q]) { |
| 116 | + k = pi[k - 1]; |
| 117 | + } |
| 118 | + if (pattern[k] == pattern[q]) { |
| 119 | + k++; |
| 120 | + } |
| 121 | + pi[q] = k; |
| 122 | + } |
| 123 | + return pi; |
| 124 | + } |
| 125 | +}; |
| 126 | +``` |
60 | 127 | <!-- end -->
|
0 commit comments