leetcode-158周赛-5222-分割字符串

题目描述:

 自己的提交:

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        if not s:return 0
        res = 0
        c = {}
        tmp = None
        for r in s:
            if not c:
                tmp = r
                c[tmp] = 1
            else:
                if r in c:
                    c[r] += 1
                else:
                    c[tmp] -= 1
            if c[tmp]==0:
                res += 1
                c.clear()
        return res

优化:

class Solution(object):
    def balancedStringSplit(self, S):
        ans = 0
        bal = 0
        for c in S:
            bal += 1 if c == 'L' else -1
            if bal == 0:
                ans += 1
        return ans

猜你喜欢

转载自www.cnblogs.com/oldby/p/11669488.html
今日推荐