zoukankan      html  css  js  c++  java
  • 32. Longest Valid Parentheses(最长括号匹配,hard)

     

    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.

    code1:

    ()():返回2

     1 class Solution:
     2     def longestValidParentheses(self, s):
     3         ans = 0
     4         stack = []
     5         for i,item in enumerate(s):
     6             if item == '(':
     7                 stack.append(i)
     8             else:
     9                 if(stack != []):
    10                     ans = max(ans,i-stack[-1]+1)
    11                     stack.pop()
    12         return ans

    code2:

    ()():返回4

    不是很理解

     1 class Solution:
     2     def longestValidParentheses(self, s):
     3         ans = 0
     4         stack = []
     5         last =-1 
     6         for i,item in enumerate(s):
     7             if item == '(':
     8                 stack.append(i)
     9             else:
    10                 if(stack == []):#已经匹配成功了
    11                     last = i
    12                 else:
    13                     stack.pop()
    14                     if stack==[]:
    15                         ans = max(ans,i-last)
    16                     else:
    17                         ans = max(ans,i-stack[-1])
    18         return ans
  • 相关阅读:
    oracle中的游标
    Oracle中的表空间
    Oracle中建表及表操作
    oracle中的权限管理
    oracle中的数据类型
    Oracle中常用的系统函数
    oracle中的dual表简介
    Oracle中常用的系统表
    Git常用命令总结
    Git配置文件与git config命令
  • 原文地址:https://www.cnblogs.com/zle1992/p/8469694.html
Copyright © 2011-2022 走看看