Longest Valid Parentheses

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.

思路:

  栈的经典应用

我的代码:

public class Solution {
    public int longestValidParentheses(String s) {
        if(s==null || s.length()==0)    return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int max = 0;
        
        for(int i=0; i<s.length(); i++)
        {
            if(stack.isEmpty() || s.charAt(stack.peek())==')' || s.charAt(i)=='(') stack.push(i);
            else
            {
                stack.pop();
                int index = stack.isEmpty()? -1 : stack.peek();
                max = Math.max(max,i-index);
            }
        }
        return max;
    }
}
View Code

他人代码:

public int longestValidParentheses(String s) {
    char[] S = s.toCharArray();
    int[] V = new int[S.length];
    int open = 0;
    int max = 0;
    for (int i=0; i<S.length; i++) {
        if (S[i] == '(') open++;
        if (S[i] == ')' && open > 0) {
            V[i] = 2 + V[i-1] + (i-2-V[i-1] > 0 ? V[i-2-V[i-1]] : 0);
            open--;
        }
        if (V[i] > max) max = V[i];
    }
    return max;
}
View Code

学习之处:

  • 不知道这道题为什么在leetcode上hard的难度,思路很容易想,代码很容易些,也一遍就AC了
  • 想的越多,最后写出来的代码越简洁
  • 看别人的代码才发现,这道题的另外一个解法使用动态规划来解, V[i-1] is its previous consecutive parentheses, i-2-V[i-1] is the position right outside this big "( ... )" part. So check if previous big "(...)" is a valid one. 
  • 改掉不好的习惯 day by day
原文地址:https://www.cnblogs.com/sunshisonghit/p/4493853.html