Maximum Equalized Substrings After One Adjacent Swap
Problem statement
You are given a string s containing only L and R.
A substring is equalized when it contains the same number of L and R characters. You may swap at most one pair of adjacent characters in s.
After the optional swap, split the entire string into consecutive, nonempty equalized substrings. Return the maximum possible number of substrings in such a split. If the complete string has different total counts of L and R, return 0 because no complete equalized split is possible.
Function
maxEqualizedSubstrings(s: String) → intExamples
Example 1
s = "RLRRLLRLRL"return = 5Swap the adjacent R and L at indices 3 and 4. The string becomes RLRLRLRLRL, which splits as RL | RL | RL | RL | RL.
Example 2
s = "RL"return = 1The whole string is already one equalized substring, and no adjacent swap can create a second nonempty part.
Example 3
s = "RRLL"return = 2Swap the middle R and L to obtain RLRL, then split it as RL | RL.
Constraints
1 <= s.length <= 2 * 10^5- Every character of
sis eitherLorR. - You may perform zero or one adjacent swap.