LeetCode - the longest active brackets

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"

Length -> associate subscript
effective brackets -> associate to stack
up -> To state length determination

s = '()(())' # 6
max_len = 0

stack = [-1]

for i , v in enumerate(s):
    if v == '(':
        stack.append(i)
    else:
        stack.pop()
        if  len(stack) == 0:
            stack.append(i)
        else:
            max_len = max(max_len, i -stack[-1])

print(max_len)

Guess you like

Origin www.cnblogs.com/yeni/p/11445791.html