1. 程式人生 > >leetcode.32 最長有效括號

leetcode.32 最長有效括號

給定一個只包含 ‘(’ 和 ‘)’ 的字串,找出最長的包含有效括號的子串的長度。

示例 1:

輸入: "(()"
輸出: 2
解釋: 最長有效括號子串為 "()"

示例 2:

輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串為 "()()"

思路:用一個數組儲存對應的字元是否已經配對,配對了的為1,沒配對為0.我們需要記錄每一個"(“的下標是多少,用另一個棧(棧2)去儲存該下標。遇到”)“的時候,配對”(",出棧(棧1)的時候,我們就可以知道通過出棧(棧2)知道對應的下標的地址是什麼了,就可以將它置為1. 最後我們統計這個陣列連續的1最長為多少即可。

  public int longestValidParentheses(String s) {
        Deque deque = new LinkedList();
        Deque indexDeque = new LinkedList();
        int[] count = new int[s.length()];
        int max = 0;
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            String ss = String.valueOf(s.charAt(i));
            if (ss.equals(")")) {
                if (deque.isEmpty()) {
                    continue;
                } else {
                    deque.pop();
                    count[i] = 1;
                    count[((Integer) indexDeque.pop()).intValue()] = 1;
                }
            } else if (ss.equals("(")) {
                deque.push(ss);
                indexDeque.push(i);
            }
        }
        for (int i = 0; i < count.length; i++) {
            if (count[i] == 0) {
                total = 0;
            } else {
                total++;
                if (total >= max) {
                    max = total;
                }
            }
        }
        return max;
    }