题目链接: https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid/.
第一次自己写的代码
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
if len(S) == 0:
return []
stack = [S[0]]
for i in range(1, len(S)):
if S[i] == "(":
stack.append("(")
else:
if "(" in stack:
stack.remove("(")
else:
stack.append(")")
return len(stack)
维护一个list,通过遍历S,对于匹配的"()“进行移除,未匹配的边括号保存在list中。
迭代版本:
无论多少层括号嵌套,如果有括号匹配,那么必出现”()"。
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
while "()" in S:
S = S.replace("()", "")
return len(S)