題目以下:數組
Given a string s of
'('
,')'
and lowercase English characters. appYour 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.spaFormally, a parentheses string is valid if and only if:code
- It is the empty string, contains only lowercase characters, or
- It can be written as
AB
(A
concatenated withB
), whereA
andB
are valid strings, or- It can be written as
(A)
, whereA
is a valid string.Example 1:orm
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:blog
Input: s = "a)b(c)d" Output: "ab(c)d"Example 3:rem
Input: s = "))((" Output: "" Explanation: An empty string is also valid.Example 4:string
Input: s = "(a(b(c)d)" Output: "a(b(c)d)"Constraints:it
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中的括號便可。io
代碼以下:
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