zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    [洛谷P1155] 双栈排序
    [洛谷P4315] 月下”毛景“树
    [洛谷P2486] [SDOI2011]染色
    [HNOI2010] 弾飞绵羊
    mysql注入总结
    cisco交换机实现端口聚合
    python为运维人员打造一个监控脚本
    复习ACCESS注入
    利用sfc文件构建网络渗透
    FTP站点设置
  • 原文地址:https://www.cnblogs.com/seyjs/p/11684002.html
Copyright © 2011-2022 走看看