[LeetCode]题解(python):032-Longest Valid Parentheses

时间:2023-03-09 00:09:37
[LeetCode]题解(python):032-Longest Valid Parentheses

题目来源


https://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.


题意分析


Input:str

Output:length

Conditions:返回最长有效子串

       有效:符合括号匹配规律


题目思路


用一个list存储左括号‘(’的位置(index),用一个变量last(起始值为0)存储某一个有效字串的开始(last不断更新),用maxlength存储全局最大长度,如果遇到右括号‘)’,

  1. 如果此时list为空,表示没有左括号与之匹配,此时length = i - last;同时更新last = i + 1(表示last之前的串没用了),将list置为空;
  2. 如果list不为空,说明可以消除,则list.pop(),pop完之后,如果list为空,说明在last之后的串都符合,length = i + 1 - last;如果list不为空,则说明list最后一个位置之后的串都符合,length = i - L[-1]
  3. 根据length与maxlength大小持续更新maxlength

AC代码(Python)


 class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
maxlength = 0
L = []
last = 0
if len(s) == 0:
return 0
for i in range(len(s)):
#print(len(s),len(L))
if s[i] == '(':
L.append(i)
elif s[i] == ')':
if len(L) == 0:
length = i - last
L = []
last = i + 1
if length > maxlength:
maxlength = length else:
L.pop()
if len(L) == 0:
length = i + 1 - last
else:
length = i - L[-1]
if length > maxlength:
maxlength = length return maxlength