LeetCode - Split a String in Balanced Strings Solution - The Coding Shala

Home >> LeetCode >> Split a String in Balanced Strings

 In this post, we will learn how to solve LeetCode's Split a String in Balanced Strings problem and will implement its solution in Java.

LeetCode - Split a String in Balanced Strings Problem

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. Return the maximum amount of split balanced strings.

Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains the same number of 'L' and 'R'.

Practice this problem on LeetCode: Click Here

LeetCode - Split a String in Balanced Strings Java Solution

Approach 1

Inside a loop, we will count L and R characters and if both counts are the same then we will make it a substring and reset our count to zero.

Java Program:

class Solution {
    public int balancedStringSplit(String s) {
        int cR = 0;
        int cL = 0;
        int ans = 0;
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == 'R') cR++;
            else cL++;
            //when substring have same L and R break it
            if(cR == cL) {
                ans++;
                cR = 0;
                cL = 0;
            }
        }
        return ans;
    }
}

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala