zoukankan      html  css  js  c++  java
  • [leetcode]Longest Valid Parentheses @ Python

    原题地址:https://oj.leetcode.com/problems/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.

    解题思路:返回括号串中合法括号串的长度。使用栈。这个解法比较巧妙,开辟一个栈,压栈的不是括号,而是未匹配左括号的索引!

    代码:

    class Solution:
        # @param s, a string
        # @return an integer
        def longestValidParentheses(self, s):
            maxlen = 0
            stack = []
            last = -1
            for i in range(len(s)):
                if s[i]=='(':
                    stack.append(i)     # push the INDEX into the stack!!!!
                else:
                    if stack == []:
                        last = i
                    else:
                        stack.pop()
                        if stack == []:
                            maxlen = max(maxlen, i-last)
                        else:
                            maxlen = max(maxlen, i-stack[len(stack)-1])
            return maxlen
  • 相关阅读:
    洛谷 P3146 [USACO16OPEN]248
    洛谷 P2633 Count on a tree
    bzoj 1040 1040: [ZJOI2008]骑士
    poj 3417 Network
    洛谷 P2149 [SDOI2009]Elaxia的路线
    2、小文件问题解决
    ☀【组件
    -_-#【JS】隐含全局变量
    -_-#flash播放器自适应
    -_-#【插件】MD5
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3780312.html
Copyright © 2011-2022 走看看