zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    python利用Trie(前缀树)实现搜索引擎中关键字输入提示(学习Hash Trie和Double-array Trie)
    利用trie树实现前缀输入提示及trie的python实现
    利用python实现简单词频统计、构建词云
    Xss-challenge-tour(1-10)
    CTFHub-SQL注入 思路
    Bugku-web40
    Buuctf-web-[极客大挑战 2019]HardSQL
    命令执行及代码执行漏洞
    CTFHub-RCE 思路&AWCTF部分web题
    upload-labs 11-12 00截断
  • 原文地址:https://www.cnblogs.com/seyjs/p/11790754.html
Copyright © 2011-2022 走看看