LeetCode921. Minimum Add to Make Parentheses Valid

题目描述:

Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, or
  • It can be written as AB (A concatenated with B), where A and Bare valid strings, or
  • It can be written as (A), where A is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4

 解题思路:

dp[i]表示i位置之前的单个括号的数量。当遇到"("时,dp[i]++,遇到")"dp[i]--,当dp[i] < 0,表示,i之前需要匹配加入的"("的数量,因为")"多了无法通过在后面加入"("进行匹配。此时dp[i] = 0,在最终结果加上这个数量。

dp[i] = \begin{cases} dp[i - 1] + 1 & \text{ if } x='('\\ dp[i -1] - 1& \text{ if } x= ')'\\ \end{cases},dp[i] = 0,res += 1,if dp[i] < 0,

Python代码:

class Solution:
    def minAddToMakeValid(self, S):
        """
        :type S: str
        :rtype: int
        """
        tem, res = 0, 0
        for x in S:
            if x == '(':
                tem += 1
            else: tem -= 1
            if tem < 0:
                res += 1
                tem = 0
        return res + tem
        

 

猜你喜欢

转载自blog.csdn.net/withing1113/article/details/84531708