• 【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
  • 相关阅读:
    [VC++]轻松搞VC之定时器(Timer)
    [VC++]VC中如何获得当前系统时间
    [VC++]如何利用this获得窗口句柄
    SMART原则
    SQL配置
    术语百科
    关于SQL锁问题
    第六代OA办公理念(摘录)
    心动机型
    SQL2008R2的索引重建
  • 原文地址:https://www.cnblogs.com/seyjs/p/11684002.html
Copyright © 2020-2023  润新知