Problem · String

Maximum Number of Operations on String

Learn this problem
MediumMathWorksFULLTIMEOA

Problem statement

Given a string s of lowercase English characters, the following operation can be performed on it 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].

- For example, if s = "aabc", then after the operation at i = 1, s = "aaac".

Find the maximum number of operations that can be applied to s.

Function

maximumNumberOfOperations(s: String) → int

Complete the function maximumNumberOfOperations in the editor.

maximumNumberOfOperations has the following parameter:

  1. String s: the string to perform operations on

Returns

int: the maximum number of operations that can be applied

Examples

Example 1

s = "accept"return = 3
The following operations are performed. Bold indicates the changed character. - In the original string, start at i = 2, "cce". The new string s' = "accpct". - Start at i = 3, s' = "acccct". - Start at i = 4 s' = "accccc". The maximum number of operations that can be applied is 3. (Not very sure about the output and explanation. If you happen to know about it, feel free to lmk! Manyyy thanks in advance! 🧡)

Example 2

s = "accept"return = 3
The following operations are performed. Bold indicates the changed character. - In the original string, start at i = 2, "cce". The new string s' = "accpct". - Start at i = 3, s' = "acccct". - Start at i = 4 s' = "accccc". The maximum number of operations that can be applied is 3. (Not very sure about the output and explanation. If you happen to know about it, feel free to lmk! Manyyy thanks in advance! 🧡)

Constraints

len of string can be up to 105

More MathWorks problems

drafts saved locally
public int maximumNumberOfOperations(String s) {
  // write your code here
}
s"accept"
expected3
checking account