You are given a balanced string s
. A balanced string is defined as a string with an equal number of 'L' and 'R' characters.
Your task is to split the input string s
into the maximum possible number of balanced substrings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: The string s can be split into "RL", "RRLL", "RL", "RL", where each substring is balanced.
Example 2:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: The string s can be split into "RL", "RRRLLRLL", where each substring is balanced.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: The string s can only be split into "LLLLRRRR", which is itself a balanced string.
Write a function that takes a balanced string s
as input and returns the maximum number of balanced substrings you can obtain.
What is the time and space complexity of your solution?
A brute-force solution would involve iterating through all possible substrings and checking if each substring is balanced. We would keep track of the maximum number of balanced substrings found. However, this approach is inefficient.
def max_balanced_substrings_naive(s):
n = len(s)
max_count = 0
for i in range(1 << (n - 1)):
count = 0
current_substring = ""
balanced = True
l_count = 0
r_count = 0
for j in range(n):
current_substring += s[j]
if s[j] == 'L':
l_count += 1
else:
r_count += 1
if (i >> j) & 1 or j == n - 1:
if l_count == r_count:
count += 1
l_count = 0
r_count = 0
else:
balanced = False
break
if balanced:
max_count = max(max_count, count)
return max_count
This is because we iterate through all possible combinations of substrings (2^(n-1)) and, for each combination, we iterate through the string (n).
In the worst case, the recursion depth can go up to n.
A more efficient approach involves iterating through the string once, keeping track of the counts of 'L' and 'R' characters. Whenever the counts are equal, we increment the number of balanced substrings.
def balancedStringSplit(s):
count = 0
balance = 0
for char in s:
if char == 'R':
balance += 1
else:
balance -= 1
if balance == 0:
count += 1
return count
We iterate through the string once.
We only use a constant amount of extra space.