You are given a string ‘S’ consisting of an equal number of ‘L’ and ‘R’ characters only. A balanced string is a string that has an equal number of ‘L’ and ‘R’ characters. You are supposed to split the given string into balanced strings. Find the maximum amount of split balanced strings possible.
Input Format :
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first input line of each test case contains the string ‘S’ denoting the given string.
Output Format :
For each test case, print an integer denoting the maximum amount of split balanced strings possible.
Print the output of each test case in a separate line.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 50
1 <= |S| <= 10000
Where S[i] is either ‘L’ or ‘R’ and '|S|' is the length of the given string.
Time limit: 1 sec
2
LRRLRL
RRLL
3
1
For the first test case, the given string can be split into “LR”, “RL” and “RL”, where each substring has an equal number of ‘L’ and ‘R’.
For the second test case, the given string can be split into “RRLL”.
2
LLRR
RL
0
1
For the first test case, the given string can be split into “LLRR”.
For the second test case, the given string can be split into “RL”.
Can you think of iterating through the string while maintaining a balance variable?
The basic idea of this approach is to iterate through the string while maintaining a variable “balance” which is initially equal to 0. Whenever we encounter ‘L we will increment the “balance” variable and similarly, whenever we encounter ‘R’ we will decrement it.
Now, let’s see an example where input string S = “LRRLRL”. Start iterating the string using a variable ‘j’.
We observe from the above explanation that the number of times the “balance” variable becomes 0 is the maximum amount of split balanced strings possible.
The steps are as follows:
O(N), Where N is the length of the input string.
Since we are traversing through the string only once, so the overall time complexity will be O(N).
O(1)
We are not using any extra space.