关注 每天一道编程题 专栏,一起学习进步。
题目
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’.
Example 2:
Input: s = “RLLLLRRRLR”
Output: 3
Explanation: s can be split into “RL”, “LLLRRR”, “LR”, each substring contains same number of ‘L’ and ‘R’.
Example 3:
Input: s = “LLLLRRRR”
Output: 1
Explanation: s can be split into “LLLLRRRR”.
Example 4:
Input: s = “RLRRRLLRLL”
Output: 2
Explanation: s can be split into “RL”, “RRRLLRLL”, since each substring contains an equal number of ‘L’ and ‘R’
Constraints:
1 <= s.length <= 1000
s[i] = 'L' or 'R'
分析
- 当s中的L和R的个数相同时(不用考虑顺序),则称s是平衡的
- “最大切分原则”,如“RLRRRLLRLL”,不能切分为RLRRRL****LRLL=3.应该切分为RL、RRRLLRLL=2
初步分析是贪心算法:
将s分成若干个小的字符串r,r中的RL个数相同,每次切分保证r的长度最大。
不理解的部分:如果是贪心,那么例一的“RLRRLLRLRL”应该直接等于1?
不会,看看评论区大神。
评论区解法:
用一个数count记录,如果为R则count++,如果为L则count–,若最终count为0,则平衡。
先从s中拿到一个字母,然后向后匹配,如果平衡,则进行下一轮,如果不平衡,则继续向后匹配。
所以不是贪心算法。
解答
评论区答案(这个慢很多,时间2ms)
class Solution {
public int balancedStringSplit(String s) {
int res = 0, cnt = 0;
for (int i = 0; i < s.length(); ++i) {
cnt += s.charAt(i) == 'L' ? 1 : -1;
if (cnt == 0) ++res;
}
return res;
}
}
我的答案(这个执行时间0ms)
class Solution {
public int balancedStringSplit(String s) {
int tmp=0;
int res=0;
for(char c :s.toCharArray()){
if (c=='R')
tmp++;
else
tmp--;
if (tmp==0)
res++;
}
return res;
}
}
将if-else改成三元表达式
class Solution {
public int balancedStringSplit(String s) {
int tmp=0;
int res=0;
for(char c :s.toCharArray()){
tmp += c=='R'?1:-1;
if(tmp==0)
res++;
}
return res;
}
}