每天两道LeetCodeHard:(5)

124 阅读2分钟

32. Longest Valid Parentheses

lc 32, 最长的合法括号对

题干:

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

解释:

hard题的题干都非常的清晰简洁,就是让你找字符串中最长的合法字串。

思考:

本来想到是用两个变量记录left和right的个数,寻找断点和合法点然后找不包含断点的最大合法路径。但是写完发现其实合法点和断点之间也是可以构成字符串的。然后就不知道怎么写了,看了别人的博客,才知道原来这种情况可以通过反向再来一遍解决。猛然醒悟解法1。时间效率是55.7%,因为遍历了两次

其实这个题还有标准解法,配对类型都可以使用栈来求解,栈中存的是左括号的位置,每次遇到右括号就pop一个出来,如果此时栈为空,则更新最大长度,否则就更新pop出来的长度;如果栈为空的时候遇到右括号,则更新start长度.时间效率70.65

这里还有一种利用dp来写的解法,实在是过于复杂,可以参考洗刷刷网友的博客:bangbingsyb.blogspot.com/2014/11/lee…

答案:

解法1:
from collections import deque
class Solution(object):
    def longestValidParentheses(self, s):
        res=0
        leftCount=0
        rightCount=0
        n=len(s)
        for i in s:
            if i=='(':
                leftCount+=1
            else:
                rightCount+=1
            if leftCount==rightCount:
                res=max(res,2*leftCount)
            elif rightCount>leftCount:
                rightCount=leftCount=0
        left=right=0
        for i in range(n-1,-1,-1):
            if s[i]=='(':
                leftCount+=1
            else:
                rightCount+=1
            if leftCount==rightCount:
                res=max(res,2*leftCount)
            elif leftCount>rightCount:
                rightCount=leftCount=0
        return res
解法2
def longestValidParentheses1(self, s):
        res,start,n=0,0,len(s)
        st = deque()
        for i in range(n):
            if s[i]=='(':
                st.append(i)
            else:
                if len(st)==0:
                    start=i+1
                else:
                    st.pop()
                    res=max(res,i-start+1) if len(st)==0 else max(res,i-st[-1])
        return res

答案补充: