LeeCode 最长有效括号

基于python3实现
LeeCode 32题

搜到的答案都是java的,试图用C实现,奈何不熟悉语法,最终还是用的python,主要参考了参考文献链接的思路,讲的很详细。
主要用的是栈,带入一段’)(()))()(‘试一下也就能理解了

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = 0
        m = []
        l = len(s)
        result = 0
        for i in range(l):
            if s[i]=='(' :
                m.append(i)
            elif s[i]==')':
                if len(m)<=0:
                    start = i+1
                else :
                    m.pop()#如果有对应的右括号就将 m中的相对应的左括号弹出
                    if len(m)<=0:
                        result = max(result,i-start+1)
                    else:
                        result = max(result,i-int(m[-1]))

        return result

参考文献:

代码题(31)— 有效的括号、括号生成、最长有效括号

猜你喜欢

转载自blog.csdn.net/duanmuji/article/details/85093400