public static int longestValidParentheses(String s) {
char[] ary = s.toCharArray();
int max = 0;
int flag = -1;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < ary.length; i++) {
if (ary[i]=='(') {
stack.push(i);
} else {
if (stack.isEmpty()) {
flag = i;
} else {
stack.pop();
if (stack.isEmpty()) {
max = Math.max(max, i-flag);
} else {
max = Math.max(max, i-stack.peek());
}
}
}
}
return max;
}
网友评论