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
  • 相关阅读:
    p67 把特定位置的位变成0,进行与运算
    p65 逻辑与运算
    JavaScript对象和初始面向对象
    JavaScript操作DOM对象
    JavaScript操作BOM对象
    JavaScript基础
    DAO模式
    使用ADO.NET访问数据库
    连接查询和分组查询
    模糊查询和聚合函数
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3780312.html
Copyright © 2011-2022 走看看