Split a String in Balanced Strings

The given problem is about finding the maximum number of balanced substrings from a given balanced string s. A balanced string is defined as having an equal number of ‘L’ and ‘R’ characters.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def balancedStringSplit(self, s: str) -> int:
        balance = 0
        count = 0

        for char in s:
            if char == 'L':
                balance += 1
            else:
                balance -= 1

            if balance == 0:
                count += 1

        return count

Explanation

We initialize two variables: balance to keep track of the balance between ‘L’ and ‘R’ characters, and count to keep track of the number of balanced substrings.

We then iterate through the string s, and for each ‘L’ we encounter, we increment the balance, and for each ‘R’ we encounter, we decrement the balance.

Whenever the balance becomes zero, that means we have found a balanced substring, so we increment the count.

Finally, we return the count, which gives the maximum number of balanced substrings we can obtain from the given string s.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# @param {String} s
# @return {Integer}
def balanced_string_split(s)
    counter = 0
    balance = 0
    characters = s.chars
    characters.each do |c|
        balance += 1 if c == 'L'
        balance -= 1 if c == 'R'
        counter += 1 if balance == 0
    end
    counter
end