LeetCode重点题系列之【32. Longest Valid Parentheses】

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

这题用stack来做,思路是初始化stack用来存放“(”的index,初始化leftmost作为最左边开始的位置,每次遇到“(”就把当前index放入stack,碰到“)”如果当前stack为空,那么就更新leftmost并进入下次循环,当前stack不为空就pop stack,如果这时stack不为空,max长度就是(i-stack[-1]),为空的话,就是i-leftmost。

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack=[]
        leftmost=-1
        maximal=0
        for index,item in enumerate(s):
            if item=="(":
                stack.append(index)
            else:
                if not stack:
                    leftmost=index
                else:
                    stack.pop()
                    if stack:
                        maximal=max(maximal,index-stack[-1])
                    else:
                        maximal=max(maximal,index-leftmost)
        return maximal

 

你可能感兴趣的:(LeetCode重点题)