
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 −
#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
- Related Articles
- Split Concatenated Strings in C++
- Split a string in Java
- Check if given string can be split into four distinct strings in Python
- How to split a string in Python
- How to split a string in Java?
- How to split a string in Golang?
- How to split string by a delimiter string in Python?
- How to split a string with a string delimiter in C#?
- Split a string in equal parts (grouper in Python)
- How to split a string in Lua programming?
- Split a string around a particular match in Java
- Python – Split Strings on Prefix Occurrence
- Split String with Dot (.) in Java
- Split String with Comma (,) in Java
- Search a string in Matrix Using Split function in Java

Advertisements