032 Longest Valid Parentheses

题目: 032 Longest Valid Parentheses

这道题是典型的堆栈应用

class Solution:
    # @param {string} s
    # @return {integer}
    def longestValidParentheses(self, s):
        stack = []
        i, last, cur_len, ans = 0, -1, 0, 0
        while i < len(s):
            if s[i] == "(":
                stack.append(i)
            else:
                if stack != []:
                    stack.pop()
                    if stack != []:
                        cur_len = i - stack[-1]
                    else:
                        cur_len = i - last
                    ans = max(ans, cur_len)
                else:
                    last = i
            i += 1
        return ans
        

 

posted @ 2015-07-14 12:40  dapanshe  阅读(117)  评论(0编辑  收藏  举报