Home > Python >Python Exercise: Split a String in Balanced Strings

Split a String in Balanced Strings

Balanced strings are those who have equal quantity of 'L' and 'R' characters. For example, 'LR', 'LLRR' and 'LRLR'. Given a balanced string s split it into the maximum amount of balanced strings and return that amount.


Example 1:

Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", 
each substring contains the same number of 'L' and 'R'.

Example 2:

Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR".

Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

Example 4:

Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL".
 

You need login to comment

Solution submitted by Dzeng at April 1, 2020, 11:57 p.m.
rcount = 0 lcount = 0 string = '' allstrings = [] count = 0 s = 'RRLLRLRLLRLLLRRRLLRLRR' for i in range(len(s)): if s[i] == 'R': rcount += 1 if s[i] == 'L': lcount += 1 string += s[i] if rcount == lcount: count += 1 allstrings.append(string) string = '' print(count, allstrings)

You need login to submit your solution