【leetcode】1249. Minimum Remove to Make Valid Parentheses

题目如下:

Given a string s of '(' , ')' and lowercase English characters. 

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, contains only lowercase characters, or
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • It can be written as (A), where A is a valid string.

Example 1:

Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Example 4:

Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

Constraints:

  • 1 <= s.length <= 10^5
  • s[i] is one of  '(' , ')' and lowercase English letters.

解题思路:本题不难,和以前很多括号问题解法类似。从头开始遍历s,如果为左括号,记录其下标,存入数组 left_unpaired中;如果是右括号,找到与其最近的左括号,并将对应左括号从left_uncompair删除,如果没有最近的括号,将右括号存入 right_unpaired中。最后,只要删掉所有存在于 left_unpaired或 right_unpaired中的括号即可。

代码如下:

class Solution(object):
    def minRemoveToMakeValid(self, s):
        """
        :type s: str
        :rtype: str
        """
        left_uncompair = []
        left_remove = {}
        right_remove = {}
        for i in range(len(s)):
            if s[i] == '(':
                left_uncompair.append(i)
                left_remove[i] = 1
            elif s[i] == ')':
                if len(left_uncompair) <= 0:
                    right_remove[i] = 1
                else:
                    inx  = left_uncompair.pop(-1)
                    del left_remove[inx]

        res = ''
        for i in range(len(s)):
            if i in right_remove or i in left_remove:
                continue
            res += s[i]
        return res

 

posted @ 2019-11-04 10:24  seyjs  阅读(834)  评论(0编辑  收藏  举报