Leetcode: 1221

less than 1 minute read

1221. Split a String in Balanced Strings

Balanced strings are those who have equal quantity of ‘L’ and ‘R’ characters.

Given a balanced string s split it in the maximum amount of balanced strings.

Return the maximum amount of splitted 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'.

Constraints:

  • 1 <= s.length <= 1000
  • s[i] = ‘L’ or ‘R’

Solutions:

class Solution {
    public int balancedStringSplit(String s) {
        int count = 0, n = 0;
        char temp = 'R';
        for(char a : s.toCharArray()){
            if(temp == a) n ++;
            else n --;      
            if( n == 0 ) count ++;
        }
        return count;
    }
}

Updated: