解题思路
只要你够贪心,就能轻松解决这道问题!既然字符串本身已经是平衡字符串,那么只要找到平衡子串,剩下的肯定也是平衡子串!那么一路贪心下去就好了,只要遍历的子串区间L和R数量相等就分割,num++,L和R再重新计数,直到最后,代码如下:
代码
class Solution {
public:
int balancedStringSplit(string s) {
int num = 0;
int count_R = 0, count_L = 0;
for(int i = 0; i < s.length(); i ++) {
if(s[i] == 'R') {
count_R ++;
} else {
count_L ++;
}
if(count_R == count_L && count_R != 0) {
count_R = 0;
count_L = 0;
num ++;
}
}
return num;
}
};
当然还可以简单优化一下,只要L和R数量保持平衡就分割,代码如下:
class Solution {
public:
int balancedStringSplit(string s) {
int num = 0, balance = 0;
for(int i = 0; i < s.length(); i ++) {
s[i] == 'L' ? balance ++ : balance --;
if(balance == 0) {
num ++;
}
}
return num;
}
};