题目
- 移除无效的括号
给你一个由 ‘(’、’)’ 和小写字母组成的字符串 s。
你需要从字符串中删除最少数目的 ‘(’ 或者 ‘)’ (可以删除任意位置的括号),使得剩下的「括号字符串」有效。
请返回任意一个合法字符串。
有效「括号字符串」应当符合以下 任意一条 要求:
空字符串或只包含小写字母的字符串
可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
(C)
变成©,下面示例用截图
提示:
1 <= s.length <= 10^5
s[i] 可能是 ‘(’、’)’ 或英文小写字母
解法
建立两个栈,分别用于存储左括号和右括号。
需要去掉的括号的情况:
- 左括号未出现前的右括号
- 右括号出现后的左括号
在遍历时,需要记住索引的位置,用enumerate
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
left_stack = []
right_stack = []
for index,item in enumerate(s):
if item == '(':
left_stack.append(index)
left_stack.append(item)
elif item == ')':
if len(left_stack):
left_stack.pop()
left_stack.pop()
else:
right_stack.append(index)
right_stack.append(item)
index_stack=[]
while left_stack:
left_stack.pop()
index_stack.append(left_stack.pop())
while right_stack:
right_stack.pop()
index_stack.append(right_stack.pop())
s = list(s)
for index in index_stack:
s[index]=''
return ''.join(s)
可以精简成一个栈来处理
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
left_stack = []
right_stack = []
for index,item in enumerate(s):
if item == '(':
left_stack.append(index)
left_stack.append(item)
elif item == ')':
if len(left_stack):
left_stack.pop()
left_stack.pop()
else:
right_stack.append(index)
right_stack.append(item)
index_stack=[]
while left_stack:
left_stack.pop()
index_stack.append(left_stack.pop())
while right_stack:
right_stack.pop()
index_stack.append(right_stack.pop())
s = list(s)
for index in index_stack:
s[index]=''
return ''.join(s)