【LeetCode】最长匹配括号字符串

最长括号匹配长度。
如果是 “ 是否 “ 的话,题目是easy,一旦是找最长,那就是hard难度了。
栈记录当前的(位置
“()((())”
关键是在断开的位置,之后可能是全新的开始((),也可能是并列的开始(),要记录长度,其实这就要求栈中不是括号,而是位置信息。
栈中的记录为:看代码下方

class Solution:    
    def longestValidParentheses(self, s: str) -> int:
        p = [-1]        
        maxn = 0
        for i in range(len(s)):
            if(s[i] == '('):
                p.append(i)
            else:
                p.pop()
                if(len(p)):
                    maxn = max(maxn, i - p[-1])
                else:
                    p.append(i)
        return maxn

栈中的状态
[-1]
[-1, 0]
[-1]
[-1, 2]
[-1, 2, 3]
[-1, 2, 3, 4]
[-1, 2, 3]

发布了178 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/ACBattle/article/details/101541535