Leetcode32. 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.

solution:用stack,复杂度O(n)

package leetcode2;

import java.util.Stack;

public class LongestValid_Parentheses {
    public static int longest_VP_DP(String s) {
        Stack<Integer> re =new Stack<Integer>();
        int start=-1;
        int maxl=0;
        int location;
        for(int i=0;i<s.length();i++){
            if (s.charAt(i)=='('){
                re.push(i);
            }else{
                if(re.empty()){
                    start=i;
                }else{
                location=re.pop();
                if(re.empty()){
                    maxl=Math.max(maxl, i-start); //外围没有(括号了,到i已得到一个局部最大值
                }else{
                    maxl=Math.max(maxl, re.peek()-i);  //外围还有(,没有结束哦
                }
                }
            }
            
        }
        return maxl;
        
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    String string="()()(";
    System.out.println(longest_VP_DP(string));
    }

}
原文地址:https://www.cnblogs.com/joannacode/p/4389328.html