動機

先把礙事的處理掉就好!!

Problem

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:

  • Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
  • Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.

In other words, we treat '(' as openning parenthesis and '))' as closing parenthesis.

For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.

You can insert the characters '(' and ')' at any position of the string to balance it if needed.

Return the minimum number of insertions needed to make s balanced.

 

Example 1:

Input: s = "(()))"Output: 1Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to to add one more ')' at the end of the string to be "(())))" which is balanced.

Example 2:

Input: s = "())"Output: 0Explanation: The string is already balanced.

Example 3:

Input: s = "))())("Output: 3Explanation: Add '(' to match the first '))', Add '))' to match the last '('.

Example 4:

Input: s = "(((((("Output: 12Explanation: Add 12 ')' to balance the string.

Example 5:

Input: s = ")))))))"Output: 5Explanation: Add 4 '(' at the beginning of the string and one ')' at the end. The string becomes "(((())))))))".

 

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of '(' and ')' only.

Sol

先把string的))換成一個新字元,剩下就是case by case

class Solution:
    def minInsertions(self, s: str) -> int:
        s = s.replace("))", "x")
        left , right, half = 0,0,0
        ret = 0
        for c in s:
            if c == "(":
                left += 1
            elif c == "x":
                if left > 0:
                    left -= 1
                else:
                    ret += 1
            else:
                if left > 0:
                    left -= 1
                    ret += 1
                else:
                    ret += 2
        return ret+left*2+right+half*2