Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into the maximum number of balanced strings.
Return the maximum number of balanced strings in such a split.
Function Signature
def balanced_string_split(s: str) -> int:
...
Rules
-
A split cuts
s
into non-empty contiguous pieces that, read in order, rebuild
s
exactly. Every character belongs to exactly one piece.
-
Every piece must be balanced.
-
Return only the count of pieces, not the pieces themselves.
Constraints
-
2 <= len(s) <= 1000
-
s[i]
is either
'L'
or
'R'
.
-
s
is a balanced string.
Examples
Input: s = "RLRRLLRLRL"
Output: 4
The string can be split into "RL", "RRLL", "RL", "RL", and each piece has as many 'L' characters as 'R' characters. No split gives more than 4 pieces.
Input: s = "RLRRRLLRLL"
Output: 2
The first piece can be "RL". In the rest, "RRRLLRLL", the 'R' characters stay ahead of the 'L' characters until the final character, so no shorter balanced piece can be cut from it. The best split is "RL", "RRRLLRLL".
Input: s = "RLLLLRRRLR"
Output: 3
The split "RL", "LLLRRR", "LR" has 3 balanced pieces. A piece may start with 'L', so the 'L' characters can run ahead too.