首页 > 学院 > 开发设计 > 正文

Feb_0219_Leetcode_32_Longest Valid Parentheses

2019-11-08 01:37:33
字体:
来源:转载
供稿:网友

Description

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.

Subscribe to see which companies asked this question

Note: The longest vaild parentheses is a substring of s

My Solution:

class Solution(object): def longestValidParentheses(self, s): if len(s) == 0: return 0 s,stack,stack_num=')'+s,[')'],[0] #加入括号的原因防止栈为空 for i in range(1, len(s)): if stack[-1]=='(' and s[i]==')': stack.pop() stack_num.pop() else: stack.append(s[i]) stack_num.append(i) stack_num.append(len(s)) res=0 for j in range(len(stack_num)-1): res=max(res,stack_num[j+1]-stack_num[j]-1) return res

思路: 1. 创建两个栈,一个用来放字符,一个用来放字符对应的索引,为了防止栈为空分别加入‘)’,0, 2.遍历字符串,如果当前的字符串的字符为‘)’并且字符栈中的最上面为的字符为‘(’,这样意味着即将匹配成功,就把栈顶的字符pop出去(可以看成是先把当前的字符压栈,再pop出去一对),否则压栈,并把对应字符的索引压到另外一个数据栈。 3.生成一个索引的list,可以发现,留下来的数据之间和匹配成功的对数有关系,即两两之间的差减一,然后就可以找到最大值


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表