921. Minimum Add to Make Parentheses Valid

A parentheses string is valid if and only if:

It is the empty string,
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.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.

For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
Return the minimum number of moves required to make s valid.

Example 1:

Input: s = "())"
Output: 1

Example 2:

Input: s = "((("
Output: 3

Example 3:

Input: s = "()"
Output: 0

Example 4:

Input: s = "()))(("
Output: 4

Constraints:

1 <= s.length <= 1000
s[i] is either '(' or ')'.

思路:与20. Valid Parentheses类似,是关于字符串匹配的问题。

想法之一就是利用堆栈。设置整数型sum,表示最少添加的括号数目。如果是左括号,压入堆栈;如果是右括号,查看堆栈栈顶元素,如果是左括号,那就证明该右括号有对应的匹配项,如果没有,(没有左括号,更不会有右括号!!),那就sum++;

堆栈中就只有左括号,又因为只有一个类型的括号匹配!一定需要用堆栈吗?不一定

该栈的作用,其实,相当于一个计数器。故上述思路就翻译成:设置一个整数型sum,表示最少添加的括号数目;设置整数型counter,表示假想stack里面的左括号数目。如果是左括号,counter++; 如果是右括号,查看counter的值,若>0,则该右括号一定有匹配的对应的左括号,则有counter--;如果=0,则证明假想stack里面,没有左括号啦。所以就要sum++

代码如下:

    public static int minAddToMakeValid(String s) {
        int sum = 0;
        int count = 0;
        if (s == null) return 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)=='(') {
                count++;
            } else {
                if (count<=0) {
                    sum = sum + 1;
                } else {
                    count--;
                }
            }
        }
        return sum + count;
    }
posted @ 2021-12-15 15:03  啤酒加点醋  阅读(25)  评论(0)    收藏  举报