堆栈为空但仍然看到 EmptyStackException

Stack empty but still see 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;
}

接受你提供的输入字符串,总是会进入while循环。

paranthesisStack.isEmpty()

在这种情况下,这将 return False 并且不会执行 while 循环。但是既然你正在使用,

!paranthesisStack.isEmpty()

这将 return True 这就是它进入 while 循环的原因。

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

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

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