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

 

 
posted @ 2021-01-11 01:21  风不再来  阅读(108)  评论(0编辑  收藏  举报