[LC] 32. 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) { if (s == null || s.length() == 0) { return 0; } LinkedList<Integer> stack = new LinkedList<>(); int j = -1, res = 0; for (int i = 0; i < s.length(); i++) { char cur = s.charAt(i); if (cur == '(') { stack.offerFirst(i); } else if (cur == ')' && stack.isEmpty()) { j = i; } else { stack.pollFirst(); if (stack.isEmpty()) { res = Math.max(res, i - j); } else { res = Math.max(res, i - stack.peekFirst()); } } } return res; } }