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