32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Example 1:
Example 2:
Example 3:
Constraints:
0 <= s.length <= 3 * 104s[i]is'(', or')'.
Solution:
class Solution {
public int longestValidParentheses(String s) {
Deque<Integer> stack = new ArrayDeque<>();
stack.offerLast(-1);
int result = 0;
for (int i = 0; i < s.length(); i++){
if (s.charAt(i) == '('){
stack.offerLast(i);
}else if (stack.size() > 1){
// stacktop is boom
stack.pollLast();
result = Math.max(result, i - stack.peekLast());
}else {
if (stack.isEmpty()){
stack.offerLast(i);
}else{
stack.pollLast();
stack.offerLast(i);
}
}
}
return result;
}
}
// TC: O(n)
// SC: O(n)