java - 堆栈为空但仍然看到 EmptyStackException
问题描述
我有下面的代码来匹配括号,你可以看到我的堆栈在它完成检查所有关闭括号时是空的,所以我的期望是它永远不应该进入 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;
}
解决方案
这是因为方法的设计findMatchingParanthesis()
:
第一个 for 循环将所有右括号压入堆栈。使用示例输入,当您进入 while 循环和第二个 for 循环时,堆栈中有四个元素。
第二个 for 循环尝试为输入中的每个字符从堆栈中取出一个元素,即 8 次。对于第五个字符,这必然会失败。
推荐阅读
- python - 是否有一种内置方法可以从 TensorFlow/Keras 中的文件加载数据增强配置?
- javascript - 如何从 cypress 测试中删除“_fs.readFileSync 不是函数”错误
- python-3.x - 有没有办法根据轴长度来缩放 pyplot.scatter 图的标记?
- proj - 安装 cdo - libproj13 丢失
- java - 修复正则表达式以允许可选字段
- javascript - 随机播放对象内的对象不起作用
- avr - 与蓝牙连接 atmega328p 的问题
- python - 如何使用 (2,3) 索引数组和 (2,3) 新值数组填充 (2,3,4) 数组的值
- github - GitHub:使用 Web 浏览器向现有拉取请求添加提交(无 git 命令)
- linux - 需要一种方法来检查文件内容(时间数据)是否超过 5 分钟