# 题目描述

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.

# 题目解答

#### 解题思想

• 遍历两遍, 第一遍把优先的’(’ 和 ‘)’ 转换成 ’ * ’ ， 然后计算最长连续的*个数
• 动态规划的思想

#### 代码实现

public class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0)
return 0;
StringBuilder temp = new StringBuilder(s);
ArrayDeque<Integer> stack = new ArrayDeque<>();
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '(')
stack.push(i);
else if(!stack.isEmpty()){
//注意
temp.setCharAt(stack.pop(), '*');
temp.setCharAt(i, '*');
}
}

int longest = 0, part = 0;
for(int i = 0; i < temp.length(); i++){
if(temp.charAt(i) == '*'){
part++;
}else {
longest = Math.max(longest, part);
part = 0;
}
}

//注意
longest = Math.max(longest, part);
return longest;
}
}

DP

public class Solution {
/**
*
1. 状态：
DP[i]：以s[i-1]为结尾的longest valid parentheses substring的长度。

2. 通项公式：
s[i-1] = '('：
DP[i] = 0

s[i-1] = ')'：找i前一个字符的最长括号串DP[i]的前一个字符j = i-2-DP[i-1]
DP[i] = DP[i-1] + 2 + DP[j]，如果j >=0，且s[j] = '('
DP[i] = 0，如果j<0，或s[j] = ')'
*/
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0 || s.length() == 1)
return 0;

int len = s.length();
int[] dp = new int[len+1];
Arrays.fill(dp, 0);

int maxLen = 0;
for(int i = 1; i < dp.length; i++){
int j = i-2-dp[i-1];
if(s.charAt(i-1) == '(' || j < 0 || s.charAt(j) == ')')
dp[i] = 0;
else {
dp[i] = dp[i-1]+2+dp[j];
maxLen = Math.max(dp[i], maxLen);
}
}

return maxLen;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Longest Valid Parentheses 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)