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.

https://leetcode.com/problems/longest-valid-parentheses/

Solution:

Analysis:

https://leetcode.com/discuss/24045/simple-java-solution

  • if open > 0 and current char is ')', then res[i] = res[i-1] + 2;
  • divide the string into 2 parts: a. 0 to i - res[i], b. i-res[i] to i
  • if the first half is valid ended at i, then res[i-res[i]] > 0; combine two half
  • if not, res[i-res[i]] = 0
public class Solution {
    public int longestValidParentheses(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }    

        // in this case, res[i] means the max length of parensis ended at i; if not, then res[i] = 0
        int[] res = new int[s.length()];
        int open = 0, max = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                open++;
                //res[i] = res[i-1];
            } else {
                if (open > 0) {
                    res[i] = res[i-1] + 2;
                    // important lines here
                    if (i >= res[i]) {
                        res[i] += res[i-res[i]];
                    }
                    open--;
                }
            }

            max = Math.max(max, res[i]);
        }

        return max;
    }
}