Leetcode: NO.32 最長有效括號 動態規劃+棧

題目

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

示例 1:

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

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

鏈接:https://leetcode-cn.com/problems/longest-valid-parentheses

解題記錄

  • 由於括號的特性,如果爲有效括號,那麼在統計過程中不會出現)的個數大於的情況
  • 由於會有左一直多於右的情況出現,這樣不會出現left==right,需要從右向左再統計一次
/**
 * @author ffzs
 * @describe
 * @date 2020/7/4
 */
public class Solution2 {
    public static int longestValidParentheses(String s) {
        char[] seq = s.toCharArray();
        int left = 0, right = 0;
        int res = 0;
        for (char c : seq) {
            if (c == '(') left ++;
            else right ++;
            if (left == right) res = Math.max(res, left*2);
            else if (left < right) left = right = 0;
        }

        left = right = 0;
        for (int i = seq.length-1; i >= 0; --i) {
            if (seq[i] == '(') left ++;
            else right ++;
            if (left == right) res = Math.max(res, left*2);
            else if (right < left) left = right = 0;
        }

        return res;
    }

    public static void main(String[] args) {
        String s = "(())()(()((";
        System.out.println(longestValidParentheses(s));
    }
}

在這裏插入圖片描述

  • 動態規劃
  • 如果)的前一個是那麼直接加上dp[i+1] = dp[i-1] + 2;
  • 如果不是那要判斷是不是(())的情況,如果是的話dp[i+1] = dp[i] + 2 + dp[i- dp[i] -1];
/**
 * @author ffzs
 * @describe
 * @date 2020/7/4
 */
public class Solution3 {
    public static int longestValidParentheses(String s) {
        int res = 0;
        char[] seq = (" "+s).toCharArray();
        int[] dp = new int[seq.length+1];
        for (int i = 1; i < seq.length; i++) {
            if (seq[i] == ')') {
                if (seq[i-1] == '(') dp[i+1] = dp[i-1] + 2;
                else if (seq[i- dp[i] -1] == '(') dp[i+1] = dp[i] + 2 + dp[i- dp[i] -1];
                res = Math.max(res, dp[i+1]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "()(())";
        System.out.println(longestValidParentheses(s));
    }
}

在這裏插入圖片描述

  • 使用棧進行統計,將將index壓入棧,彈出
  • 的前一個的index作爲哨兵
  • 每次彈出統計通過index和哨兵計算距離
  • 棧空重新設置哨兵
/**
 * @author ffzs
 * @describe
 * @date 2020/7/4
 */
public class Solution {
    public static int longestValidParentheses(String s) {
        char[] seq = s.toCharArray();
        int[] stack = new int[seq.length+1];
        stack[0] = -1;
        int res = 0, index = 1, max = 0;
        for (int i = 0; i < seq.length; i++) {
            if (seq[i] == '(') {
                stack[index++] = i;
            }
            else {
                index --;
                if (index == 0) stack[index++] = i;
                else res = Math.max(res, i - stack[index-1]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "(())()(()((";
        System.out.println(longestValidParentheses(s));
    }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章