LeetCode-32 Longest Valid Parentheses

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.

 

Hide Tags
 Dynamic Programming String
 
思路:一维动态规划求解。
设n=s.length,创建一个数组int[] valid=new int[n],
valid[i]表示以s[i]为起点,到n-1的最大合法括号序列的长度,且valid[i-1]=0;若s[i]不是合法括号序列的起点,则valid[i]==0;
 
从n-2到0,逆向求每个0<=i<=n-2的valid[i]。
1. 如果s[i]=='(',则与当前'('配对的')'位置应该是j=valid[i+1]+i+1,当然这个s[j]可能存在也可能j越界了;
2. 如果j<n&&s[j]==')',则valid[i]=valid[i+1]+2,此时valid[i]表示从i到j的最大合法括号序列的长度,因此还需要加上从j+1到n-1的最大合法括号序列长度;
3. 如果j+1<n, 则valid[i] = valid[i] + valid[j+1];
4. 如果valid[i]>max, 则max=valid[i];
 
根据以上说明,以()(((())为例,valid的值为:
       2  0  0  0  4  2  0  0 
 
代码如下:
public int longestValidParentheses(String s) {
        if(s.length() < 2) return 0;
        int n = s.length();
        int[] valid = new int[n];
        valid[n-1] = 0;
        int max = 0;
        for(int i=n-2; i>=0; i--) {
            if(s.charAt(i) == '(') {
                int j = valid[i+1] + i + 1;
                if(j < n && s.charAt(j) == ')') {
                    valid[i] = valid[i+1]+2;
                    if(j+1 < n) {
                        valid[i] = valid[i] + valid[j+1];
                    }
                } else {
                    valid[i] = 0;
                }
                max = valid[i] > max ? valid[i] : max;
            } else {
                valid[i] = 0;
            }
        }
        return max;
    }

 

 

 

posted on 2015-03-03 20:13  linxiong1991  阅读(163)  评论(0)    收藏  举报

导航