【发布时间】:2020-08-08 00:28:49
【问题描述】:
boolean Match(char c) {
if (this.type == '[' && c == ']')
return true;
if (this.type == '{' && c == '}')
return true;
if (this.type == '(' && c == ')')
return true;
return false;
}
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position)
{
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{')
{
// Process opening bracket, write your code here
Bracket temp = new Bracket(next,position);
opening_brackets_stack.push(temp);
}
if (next == ')' || next == ']' || next == '}')
{
// Process closing bracket, write your code here
try{
Bracket item = opening_brackets_stack.pop();
if(!item.Match(next))
{ //not match
System.out.println(position+1);
return;
}
}
catch(EmptyStackException e){}
}
}
// Printing answer, write your code here
try{
if(opening_brackets_stack.isEmpty())
{
System.out.println("Success");
}
else {
Bracket item = opening_brackets_stack.pop();
//print position of first unmatched opening bracket
System.out.println(item.position+1);
}
}
catch (EmptyStackException e){}
}
在括号位于最后位置的“}”、“()}”等情况下,我会得到错误的答案。 对于上述情况,我应该分别得到答案“1”,“3”,但我得到“成功”。 在所有其他情况下,它都可以正常工作。 我该怎么办?
【问题讨论】:
-
你不应该有空的 catch 块。如果发生 EmptyStackException 之一,至少打印堆栈跟踪。如果你只是忽略它们,你现在怎么知道你的代码是否只是抛出异常。
-
“我应该怎么做?” 调试你的代码。不要要求我们为您进行调试。 What is a debugger and how can it help me diagnose problems?.