32. Longest Valid Parentheses

来源:互联网 发布:数据库分析工具 编辑:程序博客网 时间:2024/05/22 13:48
# *-  coding:utf-8  -*'''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.时间复杂度:O(n)使用栈来存储'(' 与')'在字符串s中的索引值index,当*s为'('时把该索引值加入栈;否则从栈中pop一个值,d当栈为空时,把')'的索引值加入栈栈初始化时第一个值为-1,因为第j个位置与第i个位置之间有j-i+1个字符'''class Solution(object):    def longestValidParentheses(self, s):        """        :type s: str        :rtype: int        """        if s=='':    return 0    sSize=len(s)    stack=[-1]    max_len=0    for i in range(sSize):    if s[i]=='(':    stack.append(i)    else:    stack.pop()    if stack==[]:    stack.append(i)    else:    max_len=max(max_len,i-stack[-1])            return max_len    def longest(self,s):    if s=='':    return 0    sSize=len(s)    stack=[]    for i in range(0,sSize):    if s[i]=='(':    stack.append(i)    elif stack!=[] and s[stack[-1]]=='(':    stack.pop()    else:    stack.append(i)    max_len=0    rer=sSize    pre=0    print stack    if stack==[]:        return sSize    else:    while stack!=[]:    pre=stack.pop()    max_len=max(max_len,rer-pre-1)    rer=pre    max_len=max(max_len,rer)    return max_lenmyp=Solution()s=')((()))))))'  # ()(()(print myp.longestValidParentheses(s)

原创粉丝点击