1. 程式人生 > 實用技巧 >LeetCode 32 最長有效括號

LeetCode 32 最長有效括號

LeetCode32 最長有效括號

題目描述

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

樣例

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

演算法分析

思路很難想

  • 有效括號,左右括號數量相等
  • 任意字首左括號數量大於右括號數量

思路來源小呆呆

  • 若當前棧為空 或者 當前元素是'(',則直接加入棧中

  • 噹噹前元素是')'時,說明有和棧頂元素匹配的可能

    • 匹配
    • 棧不為空,彈出 stk.pop(),再更新ans = Math.max(ans, i - stk.peek())
    • 棧空,ans = Math.max(ans, i + 1)
    • 棧頂元素不能和')'匹配,則直接加入到棧中

時間複雜度\(O(n)\)

Java程式碼

class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stk = new Stack<Integer>();
        int ans = 0;
        for(int i = 0; i < s.length(); i++){
            char t = s.charAt(i);
            if(stk.isEmpty() || t == '(') stk.push(i);
            else{
                if(s.charAt(stk.peek()) == '('){
                    stk.pop();
                    if(!stk.isEmpty()) ans = Math.max(ans, i - stk.peek()); //棧不空
                    else ans = Math.max(ans, i+1); //如果棧空就是 i+1
                }else{
                    stk.push(i);
                }
            }
        }

        return ans;
    }
}