zoukankan      html  css  js  c++  java
  • 【leetcode】301. Remove Invalid Parentheses

    题目如下:

    解题思路:还是这点经验,对于需要输出整个结果集的题目,对性能要求都不会太高。括号问题的解法也很简单,从头开始遍历输入字符串并对左右括号进行计数,其中出现右括号数量大于左括号数量的情况,表示这个区间是不合法的,需要删掉一个右括号;遍历完成后,如果左括号数量大于右括号的数量,那么需要删除左括号,直至两者相等。

    代码如下:

    class Solution(object):
        def removeInvalidParentheses(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            queue = [(s,0)]
            res = []
            dic = {}
            while len(queue) > 0:
                qs,count = queue.pop(0)
                left = right = 0
                flag = False
                for i,v in enumerate(qs):
                    if v == '(':
                        left += 1
                    elif v == ')':
                        right += 1
                    if right > left:
                        for j in range(i+1):
                            if qs[j] == ')':
                                newqs = qs[:j] + qs[j+1:]
                                if (newqs, count + 1) not in queue:
                                    queue.append((newqs,count+1))
                                flag = True
                        break
                if flag == True:
                    continue
                if left == right:
                    if qs not in dic:
                        dic[qs] = 1
                        if len(res) == 0:
                            res.append((qs,count))
                        else:
                            if res[-1][1] > count:
                                res = [(qs,count)]
                            elif res[-1][1] == count:
                                res.append((qs,count))
                            else:
                                continue
                else:
                    for j, v in enumerate(qs):
                        if v == '(':
                            newqs = qs[:j] + qs[j+1:]
                            if (newqs,count+1) not in queue:
                                queue.append((newqs,count+1))
            ans = []
            for i in res:
                ans.append(i[0])
            return ans
  • 相关阅读:
    有继承的C++析构函数一定要用virtual
    CUDA vs2010配置
    lambda calculus(1)
    SICP练习1.6 1.16 解答
    用函数式来实现集合
    osx guile编译安装
    skiplist poj2892
    [转]理解 pkgconfig 工具
    专业术语解释
    【转】如何学习linux设备驱动
  • 原文地址:https://www.cnblogs.com/seyjs/p/9458691.html
Copyright © 2011-2022 走看看