【leetcode】1221. Split a String in Balanced Strings

题目如下:

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

 

posted @ 2019-10-16 10:35  seyjs  阅读(472)  评论(0编辑  收藏  举报