Given a string s of lowercase English characters, the following operation can be performed any number of times:
Choose three consecutive characters s[i], s[i+1], and s[i+2] where 1 <= i <= |s| - 2 (1-based indexing) such that s[i] = s[i+1] and s[i+1] != s[i+2]. Replace s[i+2] with s[i].
Find the maximum number of operations that can be applied to s.
Example
s = "accept"
The following operations are performed (bold indicates the changed character):
1. Start at i = 2, "cce". The new string s'="acccpt"2. Start at i = 3, s' = "acccct"
3. Start at i = 4, s'="accccc"
No other selections are available. The operation can be applied a maximum of 3 times.
Function Description
Complete the function getMaximumOperations in the editor with the following parameters:
string s: the string to transform
Returns
long int: the maximum number of times the operation can be applied
这题的核心不是模拟每一步操作,而是把字符串按“连续相同字符段”来分析。因为一次操作只会在形如 <code>xxY</code>(前两个字符相同,第三个不同)的地方,把第三个字符变成前面的字符,所以它本质上会让某一段相同字符继续向右扩展。对每个字符统计它左侧已经形成的相同字符数量,再结合当前位置是否满足可扩展条件,就能累加出总操作数。常见做法是从右向左维护 26 个字母的计数,并用前缀式的思想快速合并贡献,时间复杂度可以做到线性或近线性,适合处理大字符串。