一、问题描述
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;
本文介绍了一种使用栈来解决寻找字符串中最长有效括号子串的问题的方法。通过记录左括号的位置,并利用栈进行匹配,实现了高效查找。文章提供了详细的算法实现步骤。

422

被折叠的 条评论
为什么被折叠?



