921. 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

解答

我想到的方法是,使用一個棧來保存壓棧的數據,然後有個計數器,遇到一個符號就-1,如果遇到閉括號能與棧頂的元素成對,就不作操作。

class P921_Minimum_Add_to_Make_Parentheses_Valid {

    public int minAddToMakeValid(String S) {
        Deque<Character> stack = new ArrayDeque<>();

        int fuck = 0;

        for (char c : S.toCharArray()) {
            if (stack.isEmpty()) {
                stack.push(c);
                fuck--;
            } else {
                if (c == '(') {
                    stack.push(c);
                    fuck--;
                } else {
                    if (stack.peek() == '(') {
                        stack.pop();
                        fuck++;
                    } else {
                        fuck--;
                    }
                }
            }
        }
        return -fuck;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章