[Leetcode]Longest Valid Parentheses

本文介绍了一种使用栈来解决寻找字符串中最长合法括号序列的方法,详细解释了算法逻辑,并提供了Python代码实现。

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.

求最长的合法括号序列~用一个栈记录左括号, 右括号和index,并把stack初始为[(-1, ')')],避免之后处理stack为空的情况~ 如果当前括号是右括号且栈顶是左括号, 则把栈顶弹出并更新maxLen~

class Solution:
    # @param s, a string
    # @return an integer
    def longestValidParentheses(self, s):
        if s is None or len(s) == 0: return 0
        lenS, stack, maxLen = len(s), [(-1, ')')], 0
        for i in xrange(lenS):
            if s[i] == ')' and stack[-1][1] == '(':
                stack.pop()
                maxLen = max(maxLen, i - stack[-1][0])
            else:
                stack.append((i, s[i]))
        return maxLen


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值