本文共 774 字,大约阅读时间需要 2 分钟。
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.
Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.
Subscribe to see which companies asked this question
python
class Solution(object): def longestValidParentheses(self,s): stack=[(-1,')')] maxLen = 0 for i in range(len(s)): if s[i]==')' and stack[-1][1]=='(': stack.pop() maxLen = max(maxLen,i-stack[-1][0]) else: stack.append((i,s[i])) return maxLenCC=Solution()s="()"print CC.longestValidParentheses(s)
转载地址:http://kwqmi.baihongyu.com/