【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

猜你喜欢

转载自www.cnblogs.com/seyjs/p/9458691.html
今日推荐