Balanced strings are those who have 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 splitted balanced strings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
思路:扫描,遇见L count+1,遇见Rcount-1,只要count == 0的时候,发现一个balance string
class Solution {
public int balancedStringSplit(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int count = 0;
int maxbalance = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == 'L') {
count++;
} else {
count--;
}
if(count == 0) {
maxbalance++;
}
}
return maxbalance;
}
}