一、问题描述
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.
二、问题分析
利用Stack记录“(”,“)”的位置,而不是括号本身。
三、算法代码
Stack<Integer> stack = new Stack<Integer>();//记录'('的位置
char c;
int maxlen = 0;
int last = -1; //记录最后一个')'的位置
for(int i = 0; i < s.length(); i++){
c = s.charAt(i);
if(c == '('){
stack.push(i);
}else{
if(stack.isEmpty()){
last = i;
}else{
stack.pop();
if(stack.isEmpty()){
maxlen = Math.max(maxlen, i - last);
}else{
maxlen = Math.max(maxlen, i - stack.peek());
}
}
}
}
return maxlen;