题目描述

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.

找出一个只包含”(“和”)”的字符串中最长的有效子字符串的长度。

输入输出示例

Leetcode最长有效括号匹配---【Python】【栈】

解题思路

开辟一个栈,遍历括号字符串序列,如果遇到左括号就压入栈中;如果遇到右括号,弹出左括号,并且最大长度加2

代码实现

def longestValidParentheses(self, s):
        maxlen=0
        stack=[]
        for i in range(len(s)):
            if s[i]=='(':
                stack.append(s[i])
            if s[i]==')' and len(stack)!=0:
                stack.pop()
                maxlen+=2
        return maxlen

 

相关文章:

  • 2021-06-21
  • 2021-06-08
  • 2021-09-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2021-10-06
  • 2021-05-20
  • 2021-04-25
相关资源
相似解决方案