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.
Constraints:
1 <= s.length <= 105
s[i]
is either'('
,')'
, or lowercase English letter.
The simplest way to solve this problem is via stack. We need 2 stacks to make sure that there is no closed parenthese appears more than open parenthese or before any open parenthese.
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
right_parentheses = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif s[i] == ')':
if stack:
stack.pop()
else:
right_parentheses.append(i)
s_list = list(s)
final_remove = stack + right_parentheses
final_remove.sort(reverse=True)
for index in final_remove:
s_list.pop(index)
return "".join(s_list)
The entire idea is easy, but tricky part will be how to remove the invalid character from the given string.
My first try was like
result = ""
for i in range(len(s)):
if i not in final_remove:
result += s[i]
It works, but performance is really bad.
搶先發佈留言