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:
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 2nd and 5th substrings are not balanced.
Example 3:
Input: s = "LLLLRRRR" Output: 1 Explanation: s can be split into "LLLLRRRR".
Problem: Given a balanced string s
, split it into the maximum number of balanced substrings, where a balanced string has an equal number of 'L' and 'R' characters.
Example:
s = "RLRRLLRLRL"
4
A brute-force approach would be to iterate through all possible substrings and check if each substring is balanced. If a substring is balanced, increment the count and start searching for the next balanced substring from the end of the current substring. This approach is inefficient due to the nested loops required to generate all substrings.
A more efficient approach involves iterating through the string once, keeping track of the balance between 'L' and 'R' characters. Whenever the balance reaches zero, it indicates that a balanced substring has been found. Increment the count and continue iterating.
def balanced_string_split(s):
balance = 0
count = 0
for char in s:
if char == 'L':
balance += 1
else:
balance -= 1
if balance == 0:
count += 1
return count
# Example usage
s = "RLRRLLRLRL"
result = balanced_string_split(s)
print(f"The maximum number of balanced strings is: {result}") # Output: 4
s = "RLRRRLLRLL"
result = balanced_string_split(s)
print(f"The maximum number of balanced strings is: {result}") # Output: 2
s = "LLLLRRRR"
result = balanced_string_split(s)
print(f"The maximum number of balanced strings is: {result}") # Output: 1
The algorithm iterates through the string s
once. Therefore, the time complexity is O(n), where n is the length of the string.
The algorithm uses a constant amount of extra space to store the balance
and count
variables. Therefore, the space complexity is O(1).
def balanced_string_split(s):
if not s:
return 0
balance = 0
count = 0
for char in s:
if char == 'L':
balance += 1
elif char == 'R':
balance -= 1
else:
#Consider this an edge case, but problem statement specifies only L and R
continue #or raise an exception if input validation is required
if balance == 0:
count += 1
return count