【发布时间】:2021-08-04 08:15:50
【问题描述】:
我有下面的代码来匹配括号,你可以看到我的堆栈在它完成检查所有关闭括号时是空的,所以我的期望是它永远不应该进入 while 循环。我仍然收到空堆栈异常。我做错了什么?
public static void main(String[] args) {
boolean isParanthesisMatched = findMatchingParanthesis("[({()})]");
System.out.println("IS BALANCED? " + isParanthesisMatched);
}
public static boolean findMatchingParanthesis(String inputStr) {
boolean isParanthesisMatched = false;
Stack<Character> paranthesisStack = new Stack<Character>();
for(char ch : inputStr.toCharArray()) {
if(ch == ')' || ch == ']' || ch == '}') {
paranthesisStack.push(ch);
}
}
while(!paranthesisStack.isEmpty()) { // this should be empty after the last ) so while loop shouldn't execute
for(char ch : inputStr.toCharArray()) {
char stackElement = paranthesisStack.pop();
if(ch == '(' && stackElement == ')') {
isParanthesisMatched = true;
} else if(ch == '[' && stackElement == ']') {
isParanthesisMatched = true;
} else if(ch == '{' && stackElement == '}') {
isParanthesisMatched = true;
} else {
isParanthesisMatched = false;
}
}
}
return isParanthesisMatched;
}
【问题讨论】:
-
请跟踪堆栈。该词的正确拼写是“括号”。将变量设置为
false后应该中断。 -
java.util.Stack.peek(Stack.java:102) 处的线程“main”java.util.EmptyStackException 中的异常
-
第一个 for 循环将所有右括号压入堆栈。使用示例输入,当您进入 while 循环和第二个 for 循环时,堆栈中有四个元素。第二个 for 循环尝试为输入中的每个字符从堆栈中取出一个元素,即 8 次。对于第五个字符,这必然会失败。
-
@ThomasKläger,如果您作为回复发布,我会接受答案。非常感谢。