您的位置:首页 > Web前端

Feb_0219_Leetcode_32_Longest Valid Parentheses

2017-02-20 21:42 417 查看

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,可以发现,留下来的数据之间和匹配成功的对数有关系,即两两之间的差减一,然后就可以找到最大值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: