Longest Valid Parenthesis

来源:互联网 发布:淘宝网wap访客是 编辑:程序博客网 时间:2024/05/22 17:27

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.


11/1

An excellent problem to be done with DP in O(n) time.

use dp[i] to mean the length of the longest valid parentheses starting from i, so it is obvious that if s[i] is ')', dp[i] is 0

when s[i] is '(', check dp[i+1], if to the right of dp[i+1] + i+1 is a ')', that means the '(' at i and ')' at dp[i+1] + i+1 encircles a smaller valid parentheses of length dp[i+1], so dp[i] should be now dp[i+1] + 2

then again check the right of the ')' at dp[i+1]+i+1, and add the dp[dp[i+1]+i+2] if that is non-zero

public class Solution {    public int longestValidParentheses(String s) {        // dp[i] means the length of the longest matching parentheses starting from i        int len = s.length();        int[] dp = new int[len];                for(int i=len-1; i>=0; i--){            char ch = s.charAt(i);            if(ch == ')')       dp[i] = 0;            else if(ch == '('){                // check dp[i+1]                if(i+1 < len){                    int right = dp[i+1] + i+1;                    if(right < len && s.charAt(right) == ')'){                        dp[i] = (dp[i+1] + 2);                        right++;                        if(right < len){                            dp[i] += dp[right];                        }                    }                }            }        }                int max = 0;        for(int i=0; i<len; i++){            if(dp[i] > max)     max = dp[i];        }                return max;    }}


0 0
原创粉丝点击