You are given a balanced string s
consisting of only 'L' and 'R' characters. A balanced string is defined as a string with an equal number of 'L' and 'R' characters. Your task is to split the given string s
into the maximum number of balanced substrings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: The string can be split into "RL", "RRLL", "RL", "RL", where each substring is balanced.
Example 2:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: The string can be split into "RL", "RRRLLRLL", where each substring is balanced.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: The string can only be split into the entire string "LLLLRRRR", which is balanced.
Constraints:
s
is between 2 and 1000, inclusive.s
is either 'L' or 'R'.s
is guaranteed to be 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 by splitting the string.
A brute force approach would be to iterate through all possible substrings and check if each substring is balanced. We can keep track of the number of balanced substrings found and return the maximum possible number.
def balanced_string_split_naive(s):
count = 0
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
sub = s[i:j]
l_count = sub.count('L')
r_count = sub.count('R')
if l_count == r_count and l_count > 0:
count += 1
return count
O(n^3), where n is the length of the string. This is due to the nested loops and the count
method within the inner loop, each potentially taking O(n) time.
O(n), where n is the length of the string due to substring extraction.
The optimal solution involves iterating through the string once, keeping track of the counts of 'L' and 'R'. Whenever the counts are equal, we increment a counter, signaling a balanced substring.
def balanced_string_split(s):
count = 0
balance = 0
for char in s:
if char == 'L':
balance += 1
else:
balance -= 1
if balance == 0:
count += 1
return count
O(n), where n is the length of the string. This is because we iterate through the string once.
O(1), as we only use a constant amount of extra space for the count
and balance
variables.