"""
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。
示例 1:
输入: "()())()"
输出: ["()()()", "(())()"]
示例 2:
输入: "(a)())()"
输出: ["(a)()()", "(a())()"]
示例 3:
输入: ")("
输出: [""]
"""
# DFS 效率高 96%
def removeInvalidParentheses1(s):
res = []
def remove(s, ibegin, jbegin, tmp1, tmp2):
left_p = 0
right_p = 0
for i in range(ibegin, len(s)):
if s[i] == tmp1:
left_p += 1
if s[i] == tmp2:
right_p += 1
if left_p < right_p:
for j in range(jbegin, i+1):
if s[j] == tmp2 and (j==jbegin or s[j-1] !=tmp2):
remove(s[:j] + s[j+1:], i, j, tmp1, tmp2)
return
rev = s[::-1]
if tmp1 == "(":
remove(rev, 0, 0, ")", "(")
else:
res.append(rev)
remove(s, 0, 0, "(", ")")
return res
# BFS
from collections import deque
def removeInvalidParentheses2(s):
res = set()
rmL = 0 # 删除左括号的个数
rmR = 0 # 删除右括号的个数
for a in s:
if a == "(":
rmL += 1
elif a == ")":
if rmL !=0:
rmL -= 1
else:
rmR += 1
def isValid(s):
cnt = 0
for a in s:
if a == "(":
cnt += 1
elif a== ")":
cnt -= 1
if cnt <0:
return False
return True
queue = deque([(s, rmL, rmR)])
visited = set()
visited.add((s, rmL, rmR))
while queue:
tmp_s, left_p, right_p = queue.pop()
# 输出条件
if left_p == 0 and right_p == 0 and isValid(tmp_s):
res.add(tmp_s)
for i in range(len(tmp_s)):
# 为字母时候
if tmp_s[i] not in "()": continue
if tmp_s[i] == "(" and left_p > 0:
t = tmp_s[:i] + tmp_s[i + 1:]
if (t, left_p - 1, right_p) not in visited:
queue.appendleft((t, left_p - 1, right_p))
visited.add((t, left_p - 1, right_p))
if tmp_s[i] == ")" and right_p > 0:
t = tmp_s[:i] + tmp_s[i + 1:]
if (t, left_p, right_p - 1) not in visited:
queue.appendleft((t, left_p, right_p - 1))
visited.add((t, left_p, right_p - 1))
return list(res)
301_删除无效的括号
最新推荐文章于 2021-10-27 18:16:12 发布