301_删除无效的括号

"""

"""

# 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()
while queue:
tmp_s, left_p, right_p = queue.pop()
# 输出条件
if left_p == 0 and right_p == 0 and isValid(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))
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))
return list(res)


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

Lishu_cc

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
04-29 70
04-22 533

05-13 232
11-03 263
06-01 871
11-10 35
07-11 165