DEV Community

Cover image for Leet code — 1221. Split a String in Balanced Strings
Ben Pereira
Ben Pereira

Posted on • Updated on

Leet code — 1221. Split a String in Balanced Strings

Easy problem with String on leet code, the description being:

Balanced strings are those that have an equal quantity of 'L' and 'R' characters.

Given a balanced string s, split it into some number of substrings such that:

Each substring is balanced.

Return the maximum number of balanced strings you can obtain.

Constraints:

2 <= s.length <= 1000

s[i] is either 'L' or 'R'.

s is a balanced string.

The good thing is that the string is balanced, makes it much easier for you to find the maximum amount of balanced strings.

My thought process was iterating the string, gathering each char and checking if it was R, if it was I would add on a balance integer plus one, otherwise I would reduce one and every time balance goes zero I would add one to the output.

class Solution {
    public int balancedStringSplit(String s) {
        int output = 0;
        int balance = 0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='R'){
                balance++;
            } else {
                balance--;
            }
            if(balance ==0){
                output++;
            }
        }
        return output;
    }
}
Enter fullscreen mode Exit fullscreen mode

Seems pretty straight forward, if you want you can reduce boilerplate, but the idea is still the same:

class Solution {
    public int balancedStringSplit(String s) {
        int output = 0;
        int balance = 0;

        for(int i=0;i<s.length();i++){
            balance += s.charAt(i)=='R' ? 1 : -1;
            if(balance == 0) output++;
        }

        return output;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 0 ms, faster than 100.00% of Java online submissions for Split a String in Balanced Strings.

Memory Usage: 40.2 MB, less than 79.61% of Java online submissions for Split a String in Balanced Strings.

If I’m missing something or there is anything thing else to discuss feel free to drop a comment.

Top comments (0)