Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s split it into the maximum amount of balanced strings.
Find the maximum amount of split balanced strings.
Example 1:
Input: str="RLRRLLRLRL" Output: 4 Explanation: RL, RRLL, RL, RL
Approach:
Java
public class BalancedStringSplit {
public static void main(String[] args) {
String str = "RLRRLLRLRL";
int count = balancedStringSplit(str);
System.out.println(count);
}
private static int balancedStringSplit(String s) {
int n = s.length();
int cnt = 0, L = 0, R = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'R')
R++;
else if (s.charAt(i) == 'L')
L++;
// count of L and R
// are same then increment count and
// reset L and R
if (L == R) {
cnt++;
L = 0;
R = 0;
}
}
return cnt;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int balancedStringSplit(string s)
{
int n=s.size();
int cnt=0,L=0,R=0;
for(int i=0;i<n;i++)
{
if(s[i]=='R')
R++;
else if(s[i]=='L')
L++;
//count of L and R
// are same then increment count and
//reset L and R
if(L==R)
{
cnt++;
L=0;
R=0;
}
}
return cnt;
}
int main()
{
string str="RLRRLLRLRL";
int count=balancedStringSplit(str);
cout<<count<<"\n";
return 0;
}
No comments:
Post a Comment