6-2

32. The maximum validity brackets

Given a string containing only '(' and ''), find the length of the longest substring comprising an effective parentheses.

Example 1:

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

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

A good python solution:

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack = [0]
        longest = 0
        
        for c in s:
            if c == "(":
                stack.append(0)
            else:
                if len(stack) > 1:
                    val = stack.pop()
                    stack[-1] += val + 2
                    longest = max(longest, stack[-1])
                else:
                    stack = [0]

        return longest

analysis:

It uses a stack of thought: LIFO.

In case of Tim 0 left parenthesis, right parenthesis case of pop, to ensure that when there is a pair of left and right parentheses stack will not be affected.

Stack is not designed as a start empty, but retains an element is to the left and right parentheses when all match exactly, you can still save about the number of brackets, resulting in longest.

Right and left brackets each value are stored in the stack position: stack [-1].

If there is excess right bracket elements stack is reset (re-initialized to corresponding to [0]).

Guess you like

Origin www.cnblogs.com/tbgatgb/p/11122735.html
6-2
6-2
6-2
6-2