题目要求:
分析:
之前做过类似的题目,就是括号匹配,我们是用栈做的,这里依旧可以故技重施。
刚开始我没仔细看题,直接写了如下代码:
class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0)
return 0;
int count = 0;
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < s.length(); i ++) {
if(s.charAt(i) == '(') {
stack.push(i);
} else {
if(!stack.isEmpty()) {
stack.pop();
count ++;
} else {
count = count;
}
}
}
return count * 2;
}
}
结果自然是错的,因为我忽略了题目中的“子串”两个字。子串就表示有效括号得连续,即()(()这里,虽然有两对相匹配的括号,但是在该题中,答案依然为1,因为第一个有效括号跟第二个有效括号不连续。
由于一个字符串中,有效括号的子串可能不止一个,为了求出最大的子串长度,我们需要用到Math中的max方法。接下来最重要的问题是,我们该如何求出有效括号子串的长度。
要想求出长度,我们必须得知道它其实字符的下标。在这里,我们首先定义一个left,令其值等于-1(因为坐标是从0开始的),当有效括号子串结束时,用该子串的最后一个字符串的下标减去-1即为该子串的长度。
但是left并不总是等于-1的,当栈中为空,并且遍历到的字符为’ ) '时,left就等于该字符的下标。
举个例子:
注意:在这里,left指向别的坐标的前提是:此时的栈是空栈。如果此时的栈不是空栈,就表明这个栈中一定有’ ( ‘,就一定能与’ ) '进行匹配。
有的时候文字说不清楚的问题,一张图就能解决。看完上图之后,思路就非常清晰了,我们将所有的’ ( ‘都push进栈里,遇到一个’ ) '就弹出栈顶的元素。子串的长度就由此时指向的字符串的下标减去left的值即可。
具体代码如下:
class Solution {
public int longestValidParentheses(String s) {
if (s == null || s.length() < 1)
return 0;
Stack<Integer> stack = new Stack<Integer>();
int count = 0, left = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(')
stack.push(i);
else {
if (!stack.isEmpty()) {
stack.pop();
if (!stack.isEmpty())
count = Math.max(count, i - stack.peek());
else
count = Math.max(count, i - left);
} else
left = i;
}
}
return count;
}
}