最近发现Leetcode变化不少,取消了按年份排列,变成了数字序列。另外免费的试题都是网友提供的了,另有10道题需要收费才能做。
打开这个题目,发现原来提交的代码运行时间800多ms,应该是算法本身有问题。于是重写了一下,变成300多ms啦。
思路是用int left代替栈了,只要知道左括号的个数就行了。当匹配一个右括号后,不仅要看包含的括号个数,还要判断紧挨着的括号是不是完整的。
public class Solution {
public int longestValidParentheses(String s) {
int N = s.length();
if (N < 2) {
return 0;
}
int left = 0;
int[] result = new int[N + 1];
int max = 0;
for (int i = 1; i <= N; ++i) {
if (s.charAt(i - 1) == '(') {
++left;
result[i] = 0;
} else {
--left;
if (left < 0) {
result[i] = 0;
left = 0;
continue;
}
result[i] = result[i - 1] + 2;
if (result[i - result[i]] != 0) {
result[i] += result[i - result[i]];
}
}
max = max > result[i] ? max : result[i];
}
return max;
}
}