Balanced strings are those who have equal quantity of 'L' and 'R' characters.
平衡的字符串是指具有相等數(shù)量的“ L”和“ R”字符的字符串。
Given a balanced string s split it in the maximum amount of balanced strings.
給定一個平衡字符串s母蛛,它將拆分為最大數(shù)量的平衡字符串歪今。
Return the maximum amount of splitted balanced strings.
返回拆分后的平衡字符串的最大數(shù)量丹莲。
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
輸入:s =“ RLRRLLRLRL”
輸出:4
說明:s可分為“ RL”俘陷,“ RRLL”献宫,“ RL”孝扛,“ RL”列吼,每個子串包含相同數(shù)量的“ L”和“ R”。
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
輸入:s =“ RLLLLRRRLR”
輸出:3
說明:s可分為“ RL”苦始,“ LLLRRR”寞钥,“ LR”,每個子字符串包含相同數(shù)量的“ L”和“ R”陌选。
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
輸入:s =“ LLLLRRRR”
輸出:1
說明:可以分為“ LLLLRRRR”理郑。
Example 4:
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
Constraints:
- 1 <= s.length <= 1000
- s[i] = 'L' or 'R'
Solution:
class Solution:
def balancedStringSplit(self, s: str) -> int:
single = 0
ans = 0
for c in s:
if c == "R":
single += 1
else:
single -= 1
if single == 0:
ans += 1
return ans
We just need to a variable to track when the number of L and R become the same. When it happens, we add 1 to our ans.
我們只需要一個變量來跟蹤L和R的數(shù)量何時相同蹄溉。一旦相同,我們將ans加1您炉。最后返回ans柒爵。