**输入:** s = "LLLLRRRR"
**输出:** 1
**解释:** s 只能保持原样 "LLLLRRRR" 。
提示:
2 <= s.length <= 1000
s[i] = 'L' 或 'R'
s 是一个 平衡 字符串
方法一:贪心
根据题意,对于一个平衡字符串 s,若 s 能从中间某处分割成左右两个子串,若其中一个是平衡字符串,则另一个的 L 和 R 字符的数量必然是相同的,所以也一定是平衡字符串。
为了最大化分割数量,我们可以不断循环,每次从 s 中分割出一个最短的平衡前缀,由于剩余部分也是平衡字符串,我们可以将其当作 s 继续分割,直至 s 为空时,结束循环。
代码实现中,可以在遍历 s 时用一个变量 d 维护 L 和 R 字符的数量之差,当 d=0 时就说明找到了一个平衡字符串,将答案加一。
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intbalancedStringSplit(string s){ int ans = 0, d = 0; for (char ch : s) { ch == 'L' ? ++d : --d; if (d == 0) { ++ans; } } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publicintbalancedStringSplit(String s) { intans=0, d = 0; for (inti=0; i < s.length(); ++i) { charch= s.charAt(i); if (ch == 'L') { ++d; } else { --d; } if (d == 0) { ++ans; } } return ans; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution { publicintBalancedStringSplit(string s) { int ans = 0, d = 0; foreach (char ch in s) { if (ch == 'L') { ++d; } else { --d; } if (d == 0) { ++ans; } } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defbalancedStringSplit(self, s: str) -> int: ans, d = 0, 0 for ch in s: if ch == 'L': d += 1 else: d -= 1 if d == 0: ans += 1 return ans
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcbalancedStringSplit(s string) (ans int) { d := 0 for _, ch := range s { if ch == 'L' { d++ } else { d-- } if d == 0 { ans++ } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var balancedStringSplit = function(s) { let ans = 0, d = 0; for (let i = 0; i < s.length; ++i) { const ch = s[i]; if (ch === 'L') { ++d; } else { --d; } if (d === 0) { ++ans; } } return ans; };
[sol1-C]
1 2 3 4 5 6 7 8 9 10
intbalancedStringSplit(char* s) { int ans = 0, d = 0; for (int i = 0; s[i]; i++) { s[i] == 'L' ? ++d : --d; if (d == 0) { ++ans; } } return ans; }