【题目】
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.
输入只有 ‘(’ 和 ‘)’ ,求最长的有效括号。这里我们借助栈来求解,定义一个left变量来记录合法括号串的起始位置,我们遍历字符串,如果遇到左括号,则将当前下标压入栈,如果遇到右括号,如果当前栈为空,则将下一个坐标位置记录到left,如果栈不为空,则将栈顶元素取出,此时若栈为空,则更新结果和j - left 中的较大值,否则更新结果和j - 栈顶元素中的较大值。
【代码】
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int max=0;
int left = -1;
for(int j=0;j<s.length();j++){
if(s.charAt(j)=='(') stack.push(j);
else {
if (stack.isEmpty()) left=j;
else{
stack.pop();
if(stack.isEmpty()) max=Math.max(max,j-left);
else max=Math.max(max,j-stack.peek());
}
}
}
return max;
}
本文介绍了一种使用栈解决最长有效括号子串问题的方法。通过遍历字符串并利用栈记录左括号的位置,最终找到最长的有效括号子串长度。
395

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



