❓ 1221. 分割平衡字符串
难度:简单
平衡字符串 中,'L' 和 'R' 字符的数量是相同的。
给你一个平衡字符串 s,请你将它分割成尽可能多的子字符串,并满足:
- 每个子字符串都是平衡字符串。
返回可以通过分割得到的平衡字符串的 最大数量 。
示例 1:
示例 2:
示例 3:
提示:
- 2 <= s.length <= 1000
s[i] = 'L'或'R's是一个 平衡 字符串
💡思路:贪心
任意平衡字符串内的 R 和 L 数量相等:
- 定义
count记录R的数量,当前字符是R就加1,否则减1; - 当
count = 0时,说明当前的R和L数量相等,数量ans++。
🍁代码:(Java、C++)
Java
class Solution {
public int balancedStringSplit(String s) {
int count = 0, ans = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'R') count++;
else count--;
if(count == 0) ans++;
}
return ans;
}
}
C++
class Solution {
public:
int balancedStringSplit(string s) {
int count = 0, ans = 0;
for(char c : s){
if(c == 'R') count++;
else count--;
if(count == 0) ans++;
}
return ans;
}
};
🚀 运行结果:

🕔 复杂度分析:
- 时间复杂度:
O
(
n
)
O(n)
O(n),其中
n为字符串s的长度,我们仅需遍历s一次。 - 空间复杂度: O ( 1 ) O(1) O(1),只需要常数的空间存放若干变量。
题目来源:力扣。










