題目如下:
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 withB
), whereA
andB
are valid strings, or- It can be written as
(A)
, whereA
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