zoukankan      html  css  js  c++  java
  • 【leetcode】921. Minimum Add to Make Parentheses Valid

    题目如下:

    解题思路:上周都在忙着参加CTF,没时间做题,今天来更新一下博客吧。括号问题在leetcode中出现了很多,本题的解题思路和以前的括号问题一样,使用栈。遍历Input,如果是'('直接入栈;如果是')'则判断栈顶是否为'(',如果栈顶是'(',栈顶元素出栈,否则要加括号的count加1。遍历完成后,count + 栈里剩余的 '(' 的数量就是结果。

    代码如下:

    class Solution(object):
        def minAddToMakeValid(self, S):
            """
            :type S: str
            :rtype: int
            """
            stack = []
            res = 0
            for i in S:
                if i == '(':
                    stack.append(i)
                else:
                    if len(stack) > 0 and stack[-1] == '(':
                        stack.pop(-1)
                    else:
                        res += 1
            res += len(stack)
            return res
  • 相关阅读:
    跳码与一机多终端
    SCRUM REPORT DIRECTORY
    ASE Backend Review
    ASE Beta Sprint
    ASE Beta Sprint
    ASE Backend Alpha Sprint Review
    ASE Alpha Sprint
    ASE Alpha Sprint
    ASE Alpha Sprint
    ASE Alpha Sprint
  • 原文地址:https://www.cnblogs.com/seyjs/p/9796395.html
Copyright © 2011-2022 走看看