leetCode练习(32)

来源:互联网 发布:mac无法安装pkg 编辑:程序博客网 时间:2024/06/05 16:37

题目: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.

解题思路:

首先我们会想到这道理的简单形式:判断一个字符串是否匹配,我们可以借鉴这一思路。

构造一个stack,一个boolean数组temp代表s的每个字符是否有与之相匹配的字符

每当遇到‘(‘,我们将其索引压入stack,当遇到’)‘,从stack中提出上一个‘(’的索引,将这两个索引的temp[i] [j]都设为ture。最后找到temp中最长的连续true即可。

具体代码如下:

0 0