Skip to content

Latest commit

 

History

History
38 lines (33 loc) · 1.13 KB

1221.SplitaStringinBalancedStrings.md

File metadata and controls

38 lines (33 loc) · 1.13 KB

1221. Split a String in Balanced Strings

### Easy

Balanced strings are those that have an 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 split balanced strings.

class Solution {
public:
    int balancedStringSplit(string s) {
        /*       
        We can use a greedy approach here
        Algo:
            define balanced_string_count = 00;
            define 2 counters: r_count= 0 and l_count= 0
            Starting from the index 0, go through each char
                for each char seen increment the count
                when they are equal set the counter to zero and increment balanced_string_count;
            return when done;
        */
        int balanced_string_count = 0, r_count = 0, l_count = 0;
        for(int i=0; i<s.length();i++){
            if(s[i] == 'R')r_count++;
            else l_count++;
            if(r_count == l_count){
                r_count = 0;
                l_count = 0;
                balanced_string_count++;
            }
        }
        return balanced_string_count;
    }
};