32. Longest Valid Parentheses

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.

Dynamic Programming String

 
Solution using stack

The idea is to diminishing all “()” pairs. Keep the indices of unmatched ‘(‘ or ‘)’ in a stack. The difference between two indices of unmatched parenthesis is the length of a valid string in between.

class Solution {
  public int longestValidParentheses(String s) {
    int len = s.length();
    int maxLen = 0;
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < len; i++) {
      if (s.charAt(i) == '(') stack.push(i);
      else if (!stack.isEmpty() && s.charAt(stack.peek()) == '(')
        stack.pop();
      else stack.push(i);
    }

    if (stack.isEmpty())
      maxLen = len;
    else {
      int a = len, b;
      while (!stack.isEmpty()) {
        b = stack.pop();
        maxLen = Math.max(maxLen, a - b - 1);
        a = b;
      }
      maxLen = Math.max(maxLen, a);
    }
    return maxLen;
  }
}

 

DP Solution:

use a matches array to keep the max length of valid string. Do this only when you see ')'.

class Solution {
  public int longestValidParentheses(String s) {
    int[] matches = new int[s.length()];
    int open = 0;
    int max = 0;
    for (int i = 0; i < s.length(); ++i) {
      char c = s.charAt(i);
      if (c == '(')
        ++open;
      else if (open > 0) {// matches found
        matches[i] = 2 + matches[i - 1]; //add 2 each time because you found a pair.
        if (i > matches[i])
          matches[i] += matches[i - matches[i]]; //append previous valid string
        --open;
      }
      if (matches[i] > max)
        max = matches[i];
    }
    return max;
  }
}

 

 

posted @ 2016-08-17 04:33  新一代的天皇巨星  阅读(183)  评论(0编辑  收藏  举报