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"()()"
思路:Parenthesis, 就想到用stack,stack里面存的是没有配对好的括号的index;
遇见左括号,直接入栈;
遇见右括号:
如果stack不为空: 如果peek是左括号,pop stack,update maxlen = max(maxlen, j - stack.peek());
如果peek不是左括号,push(i)
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int res = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(stack.isEmpty()) {
stack.push(i);
} else {
if(c == '(') {
stack.push(i);
} else if(c == ')') {
if(!stack.isEmpty() && s.charAt(stack.peek()) == '(') {
stack.pop();
int len = stack.isEmpty() ? i + 1 : i - stack.peek();
res = Math.max(res, len);
} else {
stack.push(i);
}
}
}
}
return res;
}
}