[Solution]1221. Split a String in Balanced Strings

·

1 min read

Problem

Problem_Link

Solutions (time, space)

count L and R O(n), O(1)

class Solution {
    public int balancedStringSplit(String s) {
        int LRCounter = 0;
        int counter = 0;

        for (char i:s.toCharArray()){
            LRCounter+= i=='L' ? 1 : -1;
            if(LRCounter==0) ++counter;
        }

        return counter;
    }
}

Explanation

  1. Loop each char in the String

  2. Assume L is 1 and R is -1

  3. calculate L and R into LRCounter

  4. if LRCounter is 0, it means L and R are balanced.

  5. increase counter

  • the for statement is the same as below
       for (int i = 0; i < s.length(); ++i){
            if(s.chatAt(i)=='L'){
                ++LRCounter;
            } else {
                --LRCounter;
            }
            if(LRCounter==0) ++counter;
        }