1
+ // Runtime: 1433 ms (Top 23.41%) | Memory: 179.2 MB (Top 26.07%)
1
2
class Solution {
2
3
public:
3
4
vector<int > longestRepeating (string s, string queryCharacters, vector<int >& queryIndices) {
4
5
multiset<int > ls; // ordered set of lengths of all intervals at present
5
6
set<int > ins; // ordered set representing the left-ends of intervals
6
7
int n = s.length ();
7
8
ins.insert (n); // allow us to get length of current interval by *next(it) - *it for all cases
8
-
9
+
9
10
// initialize the ordered sets with the original string
10
11
for (int i = 0 , j = 1 ; i < n;) {
11
12
while (j < n && s[j] == s[j-1 ]) ++j;
12
13
ins.insert (i);
13
14
ls.insert (j-i);
14
15
i = j++;
15
16
}
16
-
17
- // update the string and track the length of the longest substring
17
+
18
+ // update the string and track the length of the longest substring
18
19
// by merging/splitting intervals
19
20
vector<int > ans;
20
21
for (int i = 0 ; i < queryIndices.size (); ++i) {
@@ -24,41 +25,41 @@ class Solution {
24
25
ans.push_back (*ls.rbegin ());
25
26
continue ;
26
27
}
27
-
28
+
28
29
// update the ordered sets
29
30
// 1. split the involved interval to parts: (left), self, (right)
30
- // ins = 0 3 6
31
- // s = b b b c c c
32
- // query : b
33
- // => ins = 0 3 4 6
34
- // => s = b b b b c c
35
-
31
+ // ins = 0 3 6
32
+ // s = b b b c c c
33
+ // query : b
34
+ // => ins = 0 3 4 6
35
+ // => s = b b b b c c
36
+
36
37
// find the left-end of the target interval
37
38
auto it = prev (ins.upper_bound (queryIndices[i])); // old/left interval
38
39
int oldl = *next (it) - *it; // old interval length
39
40
ls.erase (ls.find (oldl));
40
-
41
- ins.insert (queryIndices[i]); // self interval
41
+
42
+ ins.insert (queryIndices[i]); // self interval
42
43
ins.insert (queryIndices[i] + 1 ); // right interval
43
44
if (*it != queryIndices[i]) ls.insert (queryIndices[i] - *it); // left interval length
44
45
ls.insert (1 ); // self interval length
45
46
if (oldl - (queryIndices[i] - *it + 1 )) ls.insert (oldl - (queryIndices[i] - *it + 1 ) ); // right interval length
46
-
47
+
47
48
s[queryIndices[i]] = queryCharacters[i];
48
49
49
50
// 2. merge the adjacent intervals if the characters are identical
50
- // ins = 0 3 4 6
51
- // s = b b b b c c
52
- // => ins = 0 4 6
53
-
51
+ // ins = 0 3 4 6
52
+ // s = b b b b c c
53
+ // => ins = 0 4 6
54
+
54
55
it = ins.find (queryIndices[i]); // self interval
55
56
// merge self and right
56
57
if (queryIndices[i] + 1 < n && s[queryIndices[i]] == s[queryIndices[i] + 1 ]) {
57
58
ls.erase (ls.find (*next (it, 2 ) - *next (it)));
58
59
ls.erase (ls.find (1 ));
59
60
ins.erase (next (it));
60
61
ls.insert (*next (it) - *it);
61
- }
62
+ }
62
63
// merge left and self
63
64
if (it != ins.begin () && s[queryIndices[i]] == s[queryIndices[i] - 1 ]) {
64
65
ls.erase (ls.find (*next (it) - *it) );
@@ -71,4 +72,4 @@ class Solution {
71
72
}
72
73
return ans;
73
74
}
74
- };
75
+ };
0 commit comments