Problem
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
Loop each char in the String
Assume L is 1 and R is -1
calculate L and R into LRCounter
if LRCounter is 0, it means L and R are balanced.
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;
}