Problem · String

Maximum String Operations

Learn this problem
MediumMicrosoft logoMicrosoftINTERNOA
See Microsoft hiring insights

Problem statement

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.

Function

getMaximumOperations(s: String) → long

Examples

Example 1

s = "accept"return = 3

The following operations are performed (bold indicates 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.

Constraints

  • 3 ≤ length of s ≤ 2 * 10^5
  • The string s only contains lowercase English letters.

More Microsoft problems

drafts saved locally
public long getMaximumOperations(String s) {
  // Write your code here.
}
s"accept"
expected3
checking account