Leetcode1221 python

隔了超级长时间又开始更新。。

还是找地方存代码

最近在刷leetcode,主要觉得自己编程水平严重不足

这个也不会记录所有的刷过的题啦

主要是记录一下我觉得有意思比较重要的

题目描述

1221. Split a String in Balanced Strings

Easy

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:

Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
class Solution:
    def balancedStringSplit(self, s: str) -> int:
        Lnums = 0 #The number of L staying in the stack
        Rnums = 0 #The number of S staying in the stack
        numOfstr = 0
        stack = []
        for i in range(len(s)):
            if len(stack) == 0:
                if s[i] == 'L':
                    Lnums += 1
                else:
                    Rnums += 1
                stack.append(s[i])
            elif (len(stack) != 0):
                if s[i] == 'L':
                    Lnums += 1
                else:
                    Rnums += 1
                stack.append(s[i])
            if Lnums == Rnums:
                string = stack[0:-1]
                numOfstr += 1
                stack = []
            else:
                continue
        return numOfstr

大概思想就是建一个栈,不停入栈出栈,每次都判断栈内元素是否平衡,平衡了就前面的都出栈,清空栈。

比较像括号配对,但是括号配对比这个难

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值