1. 程式人生 > 其它 >LeetCode 1541. Minimum Insertions to Balance a Parentheses String

LeetCode 1541. Minimum Insertions to Balance a Parentheses String

LeetCode 1541. Minimum Insertions to Balance a Parentheses String (平衡括號字串的最少插入次數)

題目

連結

https://leetcode-cn.com/problems/minimum-insertions-to-balance-a-parentheses-string/

問題描述

給你一個括號字串 s ,它只包含字元 '(' 和 ')' 。一個括號字串被稱為平衡的當它滿足:

任何左括號 '(' 必須對應兩個連續的右括號 '))' 。
左括號 '(' 必須在對應的連續兩個右括號 '))' 之前。
比方說 "())", "())))" 和 "())))" 都是平衡的, ")()", "()))" 和 ")" 都是不平衡的。

你可以在任意位置插入字元 '(' 和 ')' 使字串平衡。

請你返回讓 s 平衡的最少插入次數。

輸入:s = ")"
輸出:1
解釋:第二個左括號有與之匹配的兩個右括號,但是第一個左括號只有一個右括號。我們需要在字串結尾額外增加一個 ')' 使字串變成平衡字串 "))" 。

示例

輸入:s = ")"
輸出:1
解釋:第二個左括號有與之匹配的兩個右括號,但是第一個左括號只有一個右括號。我們需要在字串結尾額外增加一個 ')' 使字串變成平衡字串 "))"

提示

1 <= s.length <= 10^5
s 只包含 '(' 和 ')' 。

思路

同樣思路,從左向右,不過需要注意,新增時左括號應該一直在左邊,need的奇偶性要注意。

最後輸出結果。

複雜度分析

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

程式碼

Java

    public int minInsertions(String s) {
        char[] ch = s.toCharArray();
        int need = 0;
        int ans = 0;
        for (char c : ch) {
            if (c == '(') {
                need+=2;
                if(need%2==1){
                    ans++;
                    need--;
                }
            }else {
                need--;
                if(need==-1){
                    ans++;
                    need=1;
                }
            }
        }
        return ans + need;
    }