301. Remove Invalid Parentheses
这题很好,BFS的想法很奇特,去除最少的元素使得新的string合法,也就是说从不合法的s,找到所有最短路径(删除一个值就相当于一条边)的合法的new_s。解法就是把每一次删除的所有可能性列举出来,然后挨个挨个的检测。
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
level = {s}
while True:
valid = filter(self.isvalid, level)
if valid:
return valid
level = {s[:i] + s[i+1:] for s in level for i in range(len(s))}
def isvalid(self, s):
ctr = 0
for c in s:
ctr += (c == '(') - (c == ')')
if ctr < 0:
return False
return ctr == 0