问题:LeetCode运行提示:Time Limit Exceeded
问题类别:低级错误,在循环中声明变量
while (!stack.isEmpty()) {
int index = stack.pop();
ss[index] = 0;
}
改正:问题解决,变量声明在循环之外
int index;
while (!stack.isEmpty()) {
index = stack.pop();
ss[index] = 0;
}
自己思路:较差,运行时间只超过所有提交0.93%
//使用栈做括号匹配
//和字符串等长的数组记录是否匹配
- 1.“(”: “(”的下标压栈
- 2.“)”: 栈不为空->()匹配:下标出栈,数组两个下标值设为1;
:栈为空-> 不匹配:数组此下标设置为0。
//遍历一次后,栈不为空:“(”不匹配:依次出栈,数组相应下标的值设为0。
//将匹配的数组转为字符串
//用不匹配括号切分数值(以0切分)
//找出最长的匹配
public class Solution
{
public int longestValidParentheses(String s)
{
Stack<Integer> stack = new Stack();
int count = s.length();
int[] ss = new int[count];
int big = 0;
//使用栈做括号匹配
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
//“(”的下标压栈
if ('(' == ch) {
stack.push(i);
continue;
}
if (')' == ch) {
//()匹配:两个下标值设为1
if (!stack.isEmpty()) {
int index = stack.pop();
ss[i] = 1;
ss[index] = 1;
continue;
} else {
//“)”不匹配设为0
ss[i] = 0;
continue;
}
}
}
int index;
//“(”不匹配设为0
while (!stack.isEmpty()) {
index = stack.pop();
ss[index] = 0;
}
StringBuffer status = new StringBuffer();
//将匹配的数组转为字符串
for (Integer ine:ss)
{
status.append(ine);
}
//用不匹配括号切分数值
String[] sta = status.toString().split("0");
//找出最长的匹配
for (String s1 : sta) {
if (s1.length() > big) {
big = s1.length();
}
}
return big;
}
}