LeetCode 1221. Split a String in Balanced Strings 在平衡字符串中分割字符串 (Easy)

Balanced strings are those who have equal quantity of 'L' and 'R' characters.
平衡的字符串是指具有相等数量的“ L”和“ R”字符的字符串。
Given a balanced string s split it in the maximum amount of balanced strings.
给定一个平衡字符串s,它将拆分为最大数量的平衡字符串。
Return the maximum amount of splitted balanced strings.
返回拆分后的平衡字符串的最大数量。

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”,每个子串包含相同数量的“ 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”,每个子字符串包含相同数量的“ 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的数量何时相同。一旦相同,我们将ans加1。最后返回ans。

你可能感兴趣的:(LeetCode 1221. Split a String in Balanced Strings 在平衡字符串中分割字符串 (Easy))