921. Minimum Add to Make Parentheses Valid**

921. Minimum Add to Make Parentheses Valid**

https://leetcode.com/problems/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 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

Note:

  • S.length <= 1000
  • S only consists of '(' and ')' characters.

C++ 实现 1

关于括号的题目一般想到栈来做, 题目中要求最小的值, 要么 DP/贪心, 要么想着某种策略来达到最小值. 就题目本身来说, 测试用例真的选取的很重要, 我们能从几个例子中发现一些规律. 比如左右括号要是能匹配, 那么没有问题; 如果 ) 括号找不到 '(' 括号, 或者 '(' 找不到右括号, 这个时候需要我们添加新的相匹配的括号. 使用栈来做的话, 首先如果遇到 '(' 括号, 那么就将其入栈, 等待匹配的 ')' 括号, 此时将 '(' 出栈; 如果当前遇到的是 ')' 括号, 但是此时栈为空, 说明没有匹配的 '(', 那么明显需要我们额外添加操作才行, 于是操作次数加 1. 到最后, 栈如果不为空, 说明还有一些 '(' 找不到匹配的右括号, 操作次数还要增加栈的大小.

class Solution {
public:
    int minAddToMakeValid(string S) {
        int res = 0;
        stack<int> st;
        for (int i = 0; i < S.size(); ++ i) {
            if (S[i] == '(') st.push(S[i]);
            else {
                if (st.empty()) res ++;
                else st.pop();
            }
        }
        res += st.size();
        return res;
    }
};

C++ 实现 2

来自 LeetCode Submission, 思路和 C++ 实现 1 一致, 但不使用栈.

扫描二维码关注公众号,回复: 11027455 查看本文章
class Solution {
public:
    int minAddToMakeValid(string s) {
        int a=0,b=0;
        for(int i=0; i<s.size(); i++){
            if(s[i]=='(')
                a++;
            if(s[i]==')'){
                if(a>0)
                    a--;
                else
                    b++;
            }
        }
        return a+b;
      }
};
发布了497 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/105169718