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
  • 相关阅读:
    python-操作excel之openpyxl
    python之redis
    geetest滑动验证
    vue-cookies
    谷歌浏览器安装vue插件
    axios和vuex
    概率论基础:补充(1)概率的公理化定义与随机变量的概念
    卸载 Anaconda 转用 Miniconda
    傅立叶变换
    SL-主成分分析(PCA)
  • 原文地址:https://www.cnblogs.com/seyjs/p/11684002.html
Copyright © 2011-2022 走看看