Maximum Balanced String Partitions
Last Updated :
20 Jul, 2021
Given a balanced string str of size N with an equal number of L and R, the task is to find a maximum number X, such that a given string can be partitioned into X balanced substring. A string called to be balanced if the number of ‘L’s in the string equals the number of ‘R’s.
Examples:
Input : str = “LRLLRRLRRL”
Output : 4
Explanation: { “LR”, “LLRR”, “LR”, “RL”} are the possible partitions.
Input : “LRRRRLLRLLRL”
Output : 3
Explanation: {“LR”, “RRRLLRLL”, “RL”} are the possible partitions.
Approach: The approach to solving this problem is to loop through the string and keep incrementing the count of L and R whenever encountered. Any instant when the respective counts of L and R become equal, a balanced parenthesis is formed. Thus the count of such instances gives the desired maximum possible partitions.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int BalancedPartition(string str, int n)
{
if (n == 0)
return 0;
int r = 0, l = 0;
int ans = 0;
for ( int i = 0; i < n; i++) {
if (str[i] == 'R' ) {
r++;
}
else if (str[i] = 'L' ) {
l++;
}
if (r == l) {
ans++;
}
}
return ans;
}
int main()
{
string str = "LLRRRLLRRL" ;
int n = str.size();
cout << BalancedPartition(str, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int BalancedPartition(String str, int n)
{
if (n == 0 )
return 0 ;
int r = 0 , l = 0 ;
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (str.charAt(i) == 'R' )
{
r++;
}
else if (str.charAt(i) == 'L' )
{
l++;
}
if (r == l)
{
ans++;
}
}
return ans;
}
public static void main(String[] args)
{
String str = "LLRRRLLRRL" ;
int n = str.length();
System.out.print(BalancedPartition(str, n) + "\n" );
}
}
|
Python3
def BalancedPartition(str1, n):
if (n = = 0 ):
return 0
r = 0
l = 0
ans = 0
for i in range (n):
if (str1[i] = = 'R' ):
r + = 1
elif (str1[i] = = 'L' ):
l + = 1
if (r = = l):
ans + = 1
return ans
if __name__ = = '__main__' :
str1 = "LLRRRLLRRL"
n = len (str1)
print (BalancedPartition(str1, n))
|
C#
using System;
class GFG{
static int BalancedPartition( string str, int n)
{
if (n == 0)
return 0;
int r = 0, l = 0;
int ans = 0;
for ( int i = 0; i < n; i++)
{
if (str[i] == 'R' )
{
r++;
}
else if (str[i] == 'L' )
{
l++;
}
if (r == l)
{
ans++;
}
}
return ans;
}
public static void Main()
{
string str = "LLRRRLLRRL" ;
int n = str.Length;
Console.Write(BalancedPartition(str, n) + "\n" );
}
}
|
Javascript
<script>
function BalancedPartition(str, n)
{
if (n == 0)
return 0;
let r = 0, l = 0;
let ans = 0;
for (let i = 0; i < n; i++)
{
if (str[i] == 'R' )
{
r++;
}
else if (str[i] == 'L' )
{
l++;
}
if (r == l)
{
ans++;
}
}
return ans;
}
let str = "LLRRRLLRRL" ;
let n = str.length;
document.write(BalancedPartition(str, n) + "</br>" );
</script>
|
Time Complexity: O(N)
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...