码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-161周赛-5249-移除无效的括号

时间:2019-11-04 11:44:49      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:ima   code   style   提交   flag   com   counter   turn   nbsp   

题目描述:

技术图片

 

 技术图片

 

 自己的提交:O(N)

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        #from collections import Counter
        flag = [True] * len(s)
        stack = []
        for i,v in enumerate(s):
            if v == "(":
                stack.append(i)
                flag[i] = False
            if v == ")":
                if stack:
                    flag[stack.pop()] = True
                else:
                    flag[i] = False
        res = ""
        for i in range(len(s)):
            if flag[i] == True:
                res += s[i]
        return res

优化:

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        pos = set()
        stk = []
        for i, ch in enumerate(s):
            if s[i] == (:
                stk.append(i)
            elif s[i] == ):
                if len(stk) == 0:
                    pos.add(i)
                else:
                    stk.pop()
        for p in stk:
            pos.add(p)
        ans = []
        for i, ch in enumerate(s):
            if i not in pos:
                ans.append(ch)
        return "".join(ans)

 

leetcode-161周赛-5249-移除无效的括号

标签:ima   code   style   提交   flag   com   counter   turn   nbsp   

原文地址:https://www.cnblogs.com/oldby/p/11790985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!