题目如下:

Balanced strings are those who have equal quantity of 'L' and 'R' characters.

Given a balanced string s split it in the maximum amount of balanced strings.

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'.

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'.

Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

 

Constraints:

  • 1 <= s.length <= 1000
  • s[i] = 'L' or 'R'

解题思路:从头开始遍历s,分别计算L和R的个数。如果两者相等,表示可以分成一组。

代码如下:

class Solution(object):
    def balancedStringSplit(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        r_count = 0
        l_count = 0
        for i in s:
            if i == 'R':r_count+=1
            else:l_count += 1
            if r_count == l_count and r_count != 0:
                res += 1
                r_count = l_count = 0
        return res

 

相关文章:

  • 2021-09-10
  • 2021-10-01
  • 2022-02-22
  • 2021-10-29
  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
猜你喜欢
  • 2021-07-12
  • 2022-12-23
  • 2022-12-23
  • 2022-02-11
  • 2021-12-04
  • 2021-08-21
  • 2021-10-01
相关资源
相似解决方案