https://leetcode.com/problems/longest-valid-parentheses/
来来来,先翻译一下这题
给定一个只有左括号和右括号的字符串,找出这个字符串的最大成形括号子串,即"(()()" 返回4,"()()(()()()"返回6
括号家族的另一题:https://www.jianshu.com/p/a9ad1a9e31e5
- 方法1
很巧妙的运用栈,但是这个栈不是把括号本身压入栈内,而是把字符串的index压入栈内
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int start = 0;
int res = 0;
for (int i = 0; i < s.length(); i++) {
//左括号
if (s.charAt(i) == '(') {
stack.push(i);
continue;
}
//右括号
if (stack.isEmpty()) {
//当栈内此时为空的时候,表明你这个右括号就是个多余,前面一定没有左括号跟你匹配了,老老实实从下一个i开始当做start重新计算吧
start = i + 1;
} else {
stack.pop();//此时上一个括号一定是左括号的index啊,因为只有左括号往里push了
//此时stack为空,表明刚pop出去的左括号和当前的右括号匹配了
//此时stack不为空,表明虽然pop出去一个左括号,但是还有残余没匹配的左括号在stack里面,
res = stack.isEmpty() ? Math.max(res, i - start + 1) : Math.max(res, i - stack.peek());
}
}
return res;
}
网友评论