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.
思路:其实这个题是道细节题,很多地方容易出错。本人使用的两个栈,一个栈存放String的内容,将不匹配的进栈。另一个栈存放的是string的下标,内容不匹配的下标进栈,而匹配的出栈。最后看存放下标的栈 两个数字差的最大值,注意栈中有k个数,则整个字符串有k+1,即需要做k+1次减法来求最大值。
public class Solution {
public int longestValidParentheses(String s) {
if (s == null || s.length() == 0 )return 0;
int result = 0;
int temp = 0;
Stack<Character> sk = new Stack<Character>();
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
sk.push('(');
stack.push(i);
} else if (!sk.isEmpty() && sk.pop() == '(') {
stack.pop();
} else {
stack.push(i);
sk.clear();
}
}
if (stack.isEmpty()) return s.length();
result = s.length() - stack.peek();
while (!stack.isEmpty()) {
int num1 = stack.peek();
int num2;
stack.pop();
if (stack.isEmpty()) {
num2 = -1;
} else {
num2 = stack.peek();
}
temp = num1 - num2;
if (result < temp) result = temp;
}
return result - 1;
}
}
思路2:在思路1的基础上改进一点点,存放下标的栈最开始push(-1),最后再push(s.length()),假设思路1中存放下标的栈有k个数字,则思路2有有k+2个数字,不过还是只有k+1段,缩减了些代码行数。
public class Solution {
public int longestValidParentheses(String s) {
if (s == null || s.length() == 0) return 0;
int result = 0;
Stack<Character> sk = new Stack<Character>();
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
sk.push('(');
stack.push(i);
} else if (!sk.isEmpty() && sk.pop() == '(') {
stack.pop();
} else {
stack.push(i);
sk.clear();
}
}
stack.push(s.length());
while (!stack.isEmpty()) {
int num1 = stack.peek();
int num2=0;
stack.pop();
if(!stack.isEmpty())
num2 = stack.peek();
result=result >(num1-num2)?result:(num1-num2);
}
return result - 1;
}
}