一、题目描述
- 输入 "(())()" ,输出6
- 输入"())()()",输出4
二、解题思路
- 遍历字符串
- 定义一个栈stack
- s.charAt(i)=='(' 入栈,否则判断栈是否为空
- 非空就出栈,并求出最大值,反之记下这个位置。
三、代码
- 上代码理解理解
- 利用start辅助计算最大值
class Solution { public int longestValidParentheses(String s) { //定义栈 Stack<Integer> stack = new Stack<Integer>(); int max = 0; for(int i = 0 ,start = 0;i < s.length();i ++) { //s.charAt(i) == '('入栈 if( s.charAt(i) == '(') stack.add(i); else { if(!stack.isEmpty()) { //栈非空,出栈 stack.pop(); //出栈后栈为空的 if(stack.isEmpty()) max = Math.max(max,i - start + 1); else max = Math.max(max,i - stack.peek()); } //栈为空,情况就是s.charAt(i) == ')'但没有左括号,如"())" else start = i + 1; } } return max; } }