LeetCode----Longest Valid Parentheses

来源:互联网 发布:淘宝新店如何提升信誉 编辑:程序博客网 时间:2024/05/29 13:59

Longest Valid Parentheses


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.


分析:

动态规划题。难点:理解什么样的串是合法的,知道如何判断串是合法的并知道两个合法串之间是如何被不合法的元素拆分的。要使用one-pass的方式来做,否则会超时。


代码:

class Solution(object):    def longestValidParentheses(self, s):        """        :type s: str        :rtype: int        """        st = []        maxlen = 0        last = -1        for i, v in enumerate(s):            if v == '(':                st.append(i)            else:                if not st:                    last = i                else:                    st.pop()                    if st:                        maxlen = max(maxlen, i - st[len(st) - 1])                    else:                        maxlen = max(maxlen, i - last)        return maxlen

0 0
原创粉丝点击