1. 程式人生 > 其它 >LeetCode 921. Minimum Add to Make Parentheses Valid

LeetCode 921. Minimum Add to Make Parentheses Valid

LeetCode 921. Minimum Add to Make Parentheses Valid (使括號有效的最少新增)

題目

連結

https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid/

問題描述

只有滿足下面幾點之一,括號字串才是有效的:

它是一個空字串,或者
它可以被寫成 AB (A 與 B 連線), 其中 A 和 B 都是有效字串,或者
它可以被寫作 (A),其中 A 是有效字串。
給定一個括號字串 s ,移動N次,你就可以在字串的任何位置插入一個括號。

例如,如果 s = "()))" ,你可以插入一個開始括號為 ")" 或結束括號為 "())))" 。
返回 為使結果字串 s 有效而必須新增的最少括號數。

示例

輸入:s = "())"
輸出:1

提示

1 <= s.length <= 1000
s 只包含 '(' 和 ')' 字元。

思路

從左向右,設定一個count一個need,count代表多餘的左括號,need代表需要補充的左括號。

最後的時候,多餘的左括號要補有括號,所以結果為count+need。

複雜度分析

時間複雜度 O(n)
空間複雜度 O(1)

程式碼

Java

    public int minAddToMakeValid(String s) {
        Stack<Character> stack = new Stack<>();
        char[] ch = s.toCharArray();
        int count = 0;
        int need = 0;
        for (char c : ch) {
            if (c == '(') {
                count++;
            } else {
                if (count > 0) {
                    count--;
                } else {
                    need++;
                }
            }
        }
        need += count;
        return need;
    }