Split a String in Balanced Strings Problem
Description
LeetCode Problem 1221.
Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into some number of substrings such that:
- Each substring is balanced.
Return the maximum number of balanced strings you can obtain.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.
Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2^nd and 5^th substrings are not balanced.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:
2 <= s.length <= 1000s[i]is either'L'or'R'.sis a balanced string.
Solution
Approach: Greedy Counting
Walk through the string and keep balance, the number of 'L' minus the number of 'R' since the last cut. Whenever it comes back to 0, the piece since the last cut is balanced: cut there and count one more piece.
Cutting as early as possible is never a mistake. The rest of the string is still balanced (the whole string and the piece just cut both are), so it can still be split as well as before, and taking the shortest balanced prefix leaves the most room for more pieces. Since the whole string is balanced, balance ends at 0, so the last piece is counted too.
Complexity: O(n) time and O(1) extra space.
class Solution:
def balancedStringSplit(self, s: str) -> int:
ans = balance = 0 # balance = number of 'L' minus number of 'R' since the last cut
for c in s:
balance += 1 if c == 'L' else -1
if balance == 0:
ans += 1 # cut here as early as possible
return ans