LeetCode笔记汇总
题目
在一个 平衡字符串 中,‘L’ 和 ‘R’ 字符的数量是相同的。
给你一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
注意:分割得到的每个字符串都必须是平衡字符串。
返回可以通过分割得到的平衡字符串的 最大数量 。
思路
从左到右遍历,通过变量count统计当前L和R出现的次数。出现了L,则count+1,R则-1.每当出现的L和R个数相同时,即count=0时,即得到一个最小的平衡字符串,此时ans+1。同时右边的也为平衡字符串,只需要接着向右边遍历即可。
代码
class Solution {
public int balancedStringSplit(String s) {
int ans = 0,count = 0;
for(int i = 0; i < s.length(); ++i){
char ch = s.charAt(i);
if(ch == 'L'){
count++;
}else{
count--;
}
if(count == 0){
ans++;
}
}
return ans;
}
}