【问题标题】:Stack empty but still see EmptyStackException堆栈为空但仍然看到 EmptyStackException
【发布时间】: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,如果您作为回复发布,我会接受答案。非常感谢。

标签: java stack


【解决方案1】:

这是因为findMatchingParanthesis()方法的设计:

第一个 for 循环将所有右括号压入堆栈。使用示例输入,当您进入 while 循环和第二个 for 循环时,堆栈中有四个元素。

第二个 for 循环尝试为输入中的每个字符从堆栈中取出一个元素,即 8 次。对于第五个字符,这必然会失败。

【讨论】:

    【解决方案2】:

    获取你提供的输入字符串,它会一直进入while循环。

    paranthesisStack.isEmpty()
    

    在这种情况下,这将返回 False,并且不会执行 while 循环。不过既然你在用,

    !paranthesisStack.isEmpty()
    

    这将返回 True,这就是它进入 while 循环的原因。

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 2021-07-19
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 2019-11-05
      • 1970-01-01
      相关资源
      最近更新 更多