921. Minimum Add to Make Parentheses Valid(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83867513

题目:

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 B are 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

解释:
需要补充几个括号使得括号组成的string变为valid,看到括号的题目就想用stack做怎么办。用传统的括号匹配问题,需要用一个count变量记录没有匹配的)的个数,最后返回stack的长度+count即可,其中stack的长度表示没有匹配的(的个数。
python代码:

class Solution(object):
    def minAddToMakeValid(self, S):
        """
        :type S: str
        :rtype: int
        """
        stack=[]
        count=0
        for letter in  S:
            if letter=='(':
                stack.append(letter)
            else:
                if stack:
                    stack.pop(-1)
                else:
                    count+=1
        return len(stack)+count
        

实际上不用栈,也用另一个计数器记录(的个数即可,其实也是栈的思想。
python代码:

class Solution(object):
    def minAddToMakeValid(self, S):
        """
        :type S: str
        :rtype: int
        """
        left,right=0,0
        for letter in S :
            if letter=='(':
                left+=1
            else:
                if left>0:
                    left-=1
                else:
                    right+=1
        return left+right 

c++代码:

 class Solution {
public:
    int minAddToMakeValid(string S) {
        int left=0,right=0;
        for(auto letter:S)
        {
            if (letter=='(')
                left++;
            else
            {
                if(left)
                    left--;
                else
                    right++;
            }
            
        }
        return left+right;
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83867513