https://leetcode.com/problems/minimum-add-to-make-parentheses-valid
921. Minimum Add to Make Parentheses Valid
以下三种小括号字串是有效的:
1.空字串
2.只有英文字母的字串
3.(A) 就是左右括号这种样子的字串
你可以在字串任何位置插入括号
请回传使s变成有效字串的最小插入次数
思路:
stack 用stack存取字符
如若出现()这种状况 就result-1
其他状况代表要变动 result+1
Python Code:
class Solution:
    def minAddToMakeValid(self, s: str) -> int:
        if "(" not in s and ")" not in s:
            return 0
        result = 0
        stack = []
        for b in s:
            if not stack:
                stack.append(b)
                result +=1
            elif stack[-1] == "(" and b == ")":
                stack.pop()
                result -= 1
            else:
                stack.append(b)
                result +=1
        return result
感觉有更漂亮的写法 但先这样:))))