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
  • 相关阅读:
    python 关于mysql 的 API pymysql
    Mysql
    Django的流程和命令行工具
    float属性 与position(定位)
    CSS的优先级与继承
    CSS的引入方式及选择器
    Html5 杂项
    Spring AOP之注解实现
    Spring AOP之xml 配置实现
    Java 正则表达式
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3780312.html
Copyright © 2011-2022 走看看