在一个「平衡字符串」中,‘L’ 和 ‘R’ 字符的数量是相同的。
给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
返回可以通过分割得到的平衡字符串的最大数量。
示例 1:
输入:s = “RLRRLLRLRL” 输出:4 解释:s 可以分割为 “RL”, “RRLL”, “RL”, “RL”,
每个子字符串中都包含相同数量的 ‘L’ 和 ‘R’。 示例 2:输入:s = “RLLLLRRRLR” 输出:3 解释:s 可以分割为 “RL”, “LLLRRR”, “LR”,
每个子字符串中都包含相同数量的 ‘L’ 和 ‘R’。 示例 3:输入:s = “LLLLRRRR” 输出:1 解释:s 只能保持原样 “LLLLRRRR”.
提示:
1 <= s.length <= 1000 s[i] = ‘L’ 或 ‘R’
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
一开始一直认为L/R是对称出现的,所以就有了下面的写法
class Solution {
public int balancedStringSplit(String s) {
String[] list = s.split("");
int num=0,len=0;
String tem=list[0];
for(int i=0;i<list.length;i++){
if(!tem.equals(list[i])){
tem=list[i+1];
num++;
}
}
return num;
}
}
执行测试用例通过,提交的时候失败了,然后看失败的用例L/R不是对称出现的,再次读题发现题目说的是L/R的数量相等,所以所谓的平衡就是要L/R数量相等就行了
class Solution {
public int balancedStringSplit(String s) {
int num=0;
String[] list=s.split("");
int temL=0,temR=0;
for(int i=0;i<list.length;i++){
if (list[i].equals("L")){
temL++;
}else{
temR++;
}
if (temL==temR&&temL!=0){
num++;
temL=temR=0;
}
}
return num;
}
}
再次进行优化:
class Solution {
public int balancedStringSplit(String s) {
int num=0;
int temL=0,temR=0;
for (char c:s.toCharArray()){
if (c=='L'){
temL++;
}else{
temR++;
}
if (temL==temR){
num++;
temL=temR=0;
}
}
return num;
}
}
再次精简
class Solution {
public int balancedStringSplit(String s) {
int num=0;
int LNum=0;
for (char c:s.toCharArray()){
if (c=='L'){
LNum++;
}else{
LNum--;
}
if (LNum==0){
num++;
}
}
return num;
}
}