Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
class Solution {
    public int longestValidParentheses(String s) {
        Deque<Integer> st = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            if (st.size() == 0)
                st.push(i);
            else if (s.charAt(st.peek()) == '(' && s.charAt(i) == ')')
                st.pop();
            else
                st.push(i);
        }
        if (st.size() == 0)
            return s.length();
        int end = s.length();
        int ans = 0;
        while (st.size() != 0) {
            ans = Math.max(ans, end - st.peek() - 1);
            end = st.pop();
        }
        ans = Math.max(ans, end - 0);
        return ans;
    }
}

Last updated