1221.分割平衡字符串
参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!
# 1221. 分割平衡字符串 [力扣题目链接](https://leetcode.cn/problems/split-a-string-in-balanced-strings/) 在一个 平衡字符串 中,'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". 示例 4: * 输入:s = "RLRRRLLRLL" * 输出:2 * 解释:s 可以分割为 "RL"、"RRRLLRLL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 ## 思路 这道题目看起来好像很复杂,其实是非常简单的贪心,关于贪心,我在这里[关于贪心算法,你该了解这些!](https://programmercarl.com/贪心算法理论基础.html)有详细的讲解。 从前向后遍历,只要遇到平衡子串,计数就+1,遍历一遍即可。 局部最优:从前向后遍历,只要遇到平衡子串 就统计 全局最优:统计了最多的平衡子串。 局部最优可以推出全局最优,举不出反例,那么就试试贪心。 例如,LRLR 这本身就是平衡子串 , 但要遇到LR就可以分割。 C++代码如下:class Solution {
public:
int balancedStringSplit(string s) {
int result = 0;
int count = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'R') count++;
else count--;
if (count == 0) result++;
}
return result;
}
};
class Solution {
public int balancedStringSplit(String s) {
int result = 0;
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'R') count++;
else count--;
if (count == 0) result++;
}
return result;
}
}
class Solution:
def balancedStringSplit(self, s: str) -> int:
diff = 0 #右左差值
ans = 0
for c in s:
if c == "L":
diff -= 1
else:
diff += 1
if diff == 0:
ans += 1
return ans
func balancedStringSplit(s string) int {
diff := 0 // 右左差值
ans := 0
for _, c := range s {
if c == 'L' {
diff--
}else {
diff++
}
if diff == 0 {
ans++
}
}
return ans
}
var balancedStringSplit = function(s) {
let res = 0, total = 0;//res为平衡字符串数量 total为当前"R"字符和"L"字符的数量差
for(let c of s){// 遍历字符串每个字符
//因为开始字符数量差就是0,遍历的时候要先改变数量差,否则会影响结果数量
total += c === 'R' ? 1:-1;//遇到"R",total++;遇到"L",total--
if(total === 0) res++;//只要"R""L"数量一样就可以算是一个平衡字符串
}
return res;
};