最長有效括號

原題

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

題目大意

  給定一個字符串,只包含小括號號,求最長的合法的小括號的數目。算法

解題思路

  使用棧來實現spa

代碼實現

算法實現類.net

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class Solution {

    public int longestValidParentheses(String s) {
        // 用於記錄待匹配的左括號和右括號的位置
        Stack<Integer> st = new Stack<>();
        int max = 0;
        for (int i = 0; i < s.length(); i++) {

            // 如是當前字符是右括號,而且記錄棧非空,而且前一個字符是左括號
            if (s.charAt(i) == ')' && !st.isEmpty() && s.charAt(st.peek()) == '(') {
                // 左括號出棧
                st.pop();
                // 求最大值
                max = Math.max(max, i - ((st.isEmpty()) ? -1 : st.peek()));
            }
            // 其它狀況就將字符入棧
            else {
                st.push(i);
            }
        }
        return max;
    }
}
相關文章
相關標籤/搜索