问题描述
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.
问题分析
一般来说括号匹配都是用栈来实现的,只需要记录合法序列的开头和结尾即可。
代码实现
public int longestValidParentheses(String s) {
if (s.length() == 0) return 0;
int len = 0, last = -1;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') stack.push(i);
else {
if (stack.isEmpty()) last = i;
else {
stack.pop();
if (stack.isEmpty()) len = Math.max(len, i - last);
else len = Math.max(len, i - stack.peek());
}
}
}
return len;
}
网友评论