Split a String in Balanced Strings in C++


As we know that the balanced strings are those which have equal quantity of left and right characters. Suppose we have a balanced string s split it in the maximum amount of balanced strings. We have to return the maximum amount of splitted balanced strings. So if the string is “RLRRLLRLRL”, then output will be 4. as there are four balanced strings. “RL”, “RRLL”, “RL” and “RL” each substring has equal amount of L and R.

To solve this, we will follow these steps −

  • initialize cnt := 0, and ans := 0
  • for i := 0 to size of the string
    • cnt := 0
    • for j := i to size of string −
      • if s[j] = ‘R’, then increase cnt by 1 otherwise decrease cnt by 1
      • if j – i > 0 and cnt = 0, then increase ans by 1, i := j, and break the loop
  • return ans

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
      int balancedStringSplit(string s) {
         int cnt = 0;
         int ans = 0;
         for(int i =0;i<s.size();i++){
            cnt = 0;
            for(int j = i;j<s.size();j++){
               if(s[j] == 'R')cnt++;
               else cnt--;
               if(j-i>0 && cnt == 0 ){
                  ans++;
                  i=j;
                  break;
               }
               //cout << i << " " << j <<" "<< cnt << endl;
            }
         }
         return ans;
      }
};
main(){
   Solution ob;
   cout << ob.balancedStringSplit("RLLLLRRRLR");
}

Input

"RLLLLRRRLR"

Output

3

Updated on: 29-Apr-2020

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements