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.


在valid parentheses问题中,我们可以用stack来检验括号对,也可以通过count来检验。遇到"("就加一,遇到")"就减一。找到一对括号就在最终结果上加2。
我们用value[i]来表示当前位置的最长括号。
括号之间的关系有两种,包含:() or (()) or ((()))和相离()() or ()(())。

public class Solution {
    public int longestValidParentheses(String s) {
        char[] chs = s.toCharArray();
        int[] value = new int[chs.length];
        int open = 0;
        int max = 0;
        
        for(int i=0; i < chs.length; i++){
            if(chs[i] == '(') open++;
            if(chs[i] == ')' && open > 0) {
                //包含关系,通过最近的括号长度来改变。
                // ()    dp[1] = dp[0] +2
                // (())  dp[2] = dp[1] +2 =2,  dp[3] = dp[2] +2 = 4
                value[i] = 2 + value[i-1];
                //相离关系,通过相离的括号长度来改变。
                // ()()  dp[3] = dp[3] + dp[1] = 2 + 2 = 4
                if(i-value[i] > 0){
                    value[i] += value[i-value[i]];
                }
                open--;
            }
            if(value[i] > max) max = value[i];
        }
        
        return max;
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。