[Solution]1221. Split a String in Balanced Strings
![[Solution]1221. Split a String in Balanced Strings](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fstock%2Funsplash%2F1464b29c77e7deaa78c51c59650012a6.jpeg&w=3840&q=75)
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;
}