zoukankan      html  css  js  c++  java
  • 1721. 使括号有效的最少添加

    1721. 使括号有效的最少添加

    中文English

    给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。

    从形式上讲,只有满足下面几点之一,括号字符串才是有效的:

    • 它是一个空字符串,或者
    • 它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
    • 它可以被写作 (A),其中 A 是有效字符串。

    给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。

    样例

    样例 1:

    输入: "())"
    输出: 1
    

    样例 2:

    输入: "((("
    输出: 3
    

    样例 3:

    输入: "()"
    输出: 0
    

    样例 4:

    输入: "()))(("
    输出: 4
    

    注意事项

    S.length <= 1000
    S 只包含 '(' 和 ')' 字符。

    同向型双指针 

    class Solution:
        """
        @param S: the given string
        @return: the minimum number of parentheses we must add
        """
        def minAddToMakeValid(self, S):
            # Write your code here
            if not S: return 0 
            
            length = len(S)
            count_pair = 0
            isend = False
            exist_array = []
            left, right = 0, 0
            
            for index in range(length):
                if S[index] == '(':
                    left, right = index, index
                    
                    while right < length:
                        if S[right] == ')' and right not in exist_array:
                            exist_array.append(right)
                            count_pair += 1 
                            break
                        
                        right += 1 
                        if right == length:
                            isend = True 
                    
                if isend:
                    break
        
            return length - count_pair * 2
     
  • 相关阅读:
    matlab 修改窗口logo 使用Javaframe
    matlab guide 开发心得
    判断两个集合的包含关系
    xaml 中 引用嵌套类的对象
    xaml中显示 “大括号左边” 文本
    步进电机脉冲与毫米
    最短路径:Dijkstra算法 C#
    JPA自定义sql的三种方式
    double相乘少一分的问题,BigDecimal参数传小数也会出问题
    String类小知识
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14260362.html
Copyright © 2011-2022 走看看