Longest Valid Parentheses

来源:互联网 发布:网络拒绝接入什么意思 编辑:程序博客网 时间:2024/05/18 02:07

leetcode32题:

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.

思路:直觉告诉我们需要用动态规划来解题,dp[i]表示从i开始的valid parentheses的长度,如果s[i] = ')',则dp[i] = 0,若s[i] = '(',对于s为"(((...)))"这种情况需要跳过中间完整的valid parentheses,即j = i+1+dp[i+1],如果s[j] = ')',则dp[i] = 2+dp[i+1],由于有s为“(((()()()()))”情况出现,所以还需要加上dp[j+1],即dp[i] = 2+dp[i+1]+dp[j+1],代码如下:

public class Solution {
public int longestValidParentheses(String s) {
int len = s.length();

if(len <= 0)
return 0;

int[] lonval = new int[len];

for(int i=0;i<len;i++)
{
lonval[i] = 0;
}

char[] s2c = s.toCharArray();

for(int i=len-2;i>=0;i--)
{
if(s2c[i] == ')')
lonval[i] = 0;
else if (s2c[i] == '(') {
int j = i + 1 + lonval[i + 1];
if (j >= len)
lonval[i] = 0;
else {
if (s2c[j] == ')') {
if (j < len - 1)
lonval[i] = lonval[i + 1] + 2 + lonval[j + 1];
else
lonval[i] = lonval[i + 1] + 2;
} else {
lonval[i] = 0;
}
}
}
}
int max = 0;
for(int i=0;i<len;i++)
{
if(lonval[i]>max)
max = lonval[i];
}
return max;
}
}

0 0