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

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala