首页 > 解决方案 > 堆栈为空但仍然看到 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;
}

标签: javastack

解决方案


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

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

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


推荐阅读