zoukankan      html  css  js  c++  java
  • 【leetcode】1541. Minimum Insertions to Balance a Parentheses String

    题目如下:

    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: 1
    Explanation: 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: 0
    Explanation: The string is already balanced.
    

    Example 3:

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

    Example 4:

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

    Example 5:

    Input: s = ")))))))"
    Output: 5
    Explanation: 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.

    解题思路:这种括号问题在leetcode有过很多了。思路都是一样的,用右括号去匹配之前出现过的左括号。

    代码如下:

    class Solution(object):
        def minInsertions(self, s):
            """
            :type s: str
            :rtype: int
            """
            res = 0
            left_count = 0
            right_count = 0
            for i in s:
                if i == '(':
                    if left_count == 0 or right_count == 0 :
                        left_count += 1
                    elif right_count == 1:
                        res += 1
                        right_count -= 1
                    else:right_count -= 2
                else:
                    if left_count == 0:
                        left_count += 1
                        right_count += 1
                        res += 1
                    elif right_count == 0:
                        right_count += 1
                    elif right_count == 1:
                        left_count -= 1
                        right_count -= 1
            if left_count > 0 :
                res += (left_count*2 - right_count)
    
            return res
  • 相关阅读:
    包 (package)
    Object类
    异常
    接口
    抽象类
    多态(经典案例)
    三大特性:(经典代码)
    对象创建的过程(重点理解)
    final关键字
    cocos2dx工程中接入支付宝sdk
  • 原文地址:https://www.cnblogs.com/seyjs/p/13667795.html
Copyright © 2011-2022 走看看