The problem is taken from LeetCode, and it states:
1221. Split a String in Balanced Strings
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.
Example:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:
1 <= s.length <= 1000
s[i]
is either ‘L’ or ‘R’.s
is a balanced string.s
is guaranteed to be balanced.0
.0
, increment the count of balanced strings.The time complexity of this algorithm is O(n) where n
is the length of the input string s
. This is because we iterate through the string once. The space complexity is O(1) since we are using a constant amount of extra space.
def balancedStringSplit(s: str) -> int:
balance = 0
max_splits = 0
for char in s:
if char == 'R':
balance += 1
elif char == 'L':
balance -= 1
if balance == 0:
max_splits += 1
return max_splits
# Example usage
example_input_1 = "RLRRLLRLRL"
print(balancedStringSplit(example_input_1)) # Output: 4
example_input_2 = "RLLLLRRRLR"
print(balancedStringSplit(example_input_2)) # Output: 3
example_input_3 = "LLLLRRRR"
print(balancedStringSplit(example_input_3)) # Output: 1
This code effectively splits the given string into the maximum number of balanced substrings by maintaining a running balance of ‘L’ and ‘R’ characters and incrementing the split count every time this balance reaches zero.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?