lc32.java 1.9 KB
Newer Older
L
liu13 已提交
1 2 3 4 5
package code;

import java.util.Stack;

/*
L
liu13 已提交
6
 * 32. Longest Valid Parentheses
L
liu13 已提交
7
 * 题意:最长括号匹配
L
liu13 已提交
8 9 10 11
 * 难度:Hard
 * 分类:Dynamic Programming, String
 * 思路:两种常规方法,一是dp,每个位置记录以该位置结尾的最长长度。另一种是用栈,把位置索引入栈。
 * Tips:想到了用dp,也想到了用数组记录位置结尾的解,但没有想好如何进行更新迭代计算。把位置索引入栈的方法很典型,关注一下。
L
liu13 已提交
12
 *      lc32, lc22, lc301
L
liu13 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 */
public class lc32 {
    public static void main(String[] args) {
        System.out.println(longestValidParentheses2("()(())"));
    }

    public static int longestValidParentheses(String s) {
        if(s.length()==0)
            return 0;
        // dp 方法
        int[] dp = new int[s.length()+1];
        int res=0;
        for (int i = 2; i <dp.length; i++) {
            if(s.charAt(i-1)=='(')
                dp[i] = 0;
            else{
                if(s.charAt(i-2)=='('){ // 这种情况:(())()
                    dp[i] = dp[i-2]+2;
L
liu13 已提交
31
                }else if(i-2-dp[i-1]>=0 && s.charAt(i-2-dp[i-1])=='('){ // 这种情况:()(()) , 第一个判断是判断索引是否合法
L
liu13 已提交
32 33 34 35 36 37 38 39 40 41 42 43
                    dp[i] = dp[i-1] + dp[i-2-dp[i-1]]+2;
                }
            }
            if(dp[i]>res)
                res = dp[i];
        }
        return res;
    }

    public static int longestValidParentheses2(String s) {
        //栈方法  ()(())
        Stack<Integer> st = new Stack();
L
liu13 已提交
44
        st.add(-1); //栈内先入-1
L
liu13 已提交
45 46 47 48
        int res = 0;
        for (int i = 0; i < s.length() ; i++) {
            char ch = s.charAt(i);
            if(ch=='(')
L
liu13 已提交
49
                st.push(i);
L
liu13 已提交
50 51
            else if(ch==')'){
                st.pop();
L
liu13 已提交
52
                if(st.isEmpty())    //截断一下
L
liu13 已提交
53 54 55 56 57 58 59
                    st.push(i);
                res = Math.max(res,i-st.peek());
            }
        }
        return res;
    }
}