3
vector<int> longestRepeating(string s, string queryCharacters, vector<int> &queryIndices) {4
multiset<int> ls; // ordered set of lengths of all intervals at present5
set<int> ins; // ordered set representing the left-ends of intervals7
ins.insert(n); // allow us to get length of current interval by *next(it) -10
// initialize the ordered sets with the original string11
for (int i = 0, j = 1; i < n;) {12
while (j < n && s[j] == s[j - 1]) ++j;18
// update the string and track the length of the longest substring19
// by merging/splitting intervals21
for (int i = 0; i < queryIndices.size(); ++i) {22
// If the querying character does not change the string:23
// do nothing for the sets24
if (queryCharacters[i] == s[queryIndices[i]]) {25
ans.push_back(*ls.rbegin());29
// update the ordered sets30
// 1. split the involved interval to parts: (left), self, (right)37
// find the left-end of the target interval38
auto it = prev(ins.upper_bound(queryIndices[i])); // old/left interval39
int oldl = *next(it) - *it; // old interval length40
ls.erase(ls.find(oldl));42
ins.insert(queryIndices[i]); // self interval43
ins.insert(queryIndices[i] + 1); // right interval44
if (*it != queryIndices[i]) ls.insert(queryIndices[i] - *it); // left interval length45
ls.insert(1); // self interval length46
if (oldl - (queryIndices[i] - *it + 1))47
ls.insert(oldl - (queryIndices[i] - *it + 1)); // right interval length49
s[queryIndices[i]] = queryCharacters[i];51
// 2. merge the adjacent intervals if the characters are identical56
it = ins.find(queryIndices[i]); // self interval57
// merge self and right58
if (queryIndices[i] + 1 < n && s[queryIndices[i]] == s[queryIndices[i] + 1]) {59
ls.erase(ls.find(*next(it, 2) - *next(it)));62
ls.insert(*next(it) - *it);64
// merge left and self65
if (it != ins.begin() && s[queryIndices[i]] == s[queryIndices[i] - 1]) {66
ls.erase(ls.find(*next(it) - *it));67
ls.erase(ls.find(*it - *prev(it)));68
ls.insert(*next(it) - *prev(it));71
ans.push_back(*ls.rbegin());