[LeetCode题解] 921. 使括号有效的最少添加

题目链接: 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) == 0return []
        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)
发布了10 篇原创文章 · 获赞 0 · 访问量 129

猜你喜欢

转载自blog.csdn.net/m0_46134602/article/details/103820407