给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
思路:用一个数组存储对应的字符是否已经配对,配对了的为1,没配对为0.我们需要记录每一个"(“的下标是多少,用另一个栈(栈2)去存储该下标。遇到”)“的时候,配对”(",出栈(栈1)的时候,我们就可以知道通过出栈(栈2)知道对应的下标的地址是什么了,就可以将它置为1. 最后我们统计这个数组连续的1最长为多少即可。
public int longestValidParentheses(String s) {
Deque deque = new LinkedList();
Deque indexDeque = new LinkedList();
int[] count = new int[s.length()];
int max = 0;
int total = 0;
for (int i = 0; i < s.length(); i++) {
String ss = String.valueOf(s.charAt(i));
if (ss.equals(")")) {
if (deque.isEmpty()) {
continue;
} else {
deque.pop();
count[i] = 1;
count[((Integer) indexDeque.pop()).intValue()] = 1;
}
} else if (ss.equals("(")) {
deque.push(ss);
indexDeque.push(i);
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] == 0) {
total = 0;
} else {
total++;
if (total >= max) {
max = total;
}
}
}
return max;
}