【问题标题】:Getting wrong output in a test case in Chech brackets in code在代码中的 Chech 括号中的测试用例中得到错误的输出
【发布时间】:2020-08-08 00:28:49
【问题描述】:
boolean Match(char c) {
    if (this.type == '[' && c == ']')
        return true;
    if (this.type == '{' && c == '}')
        return true;
    if (this.type == '(' && c == ')')
        return true;
    return false;
}




    Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
    for (int position = 0; position < text.length(); ++position) 
    {
        char next = text.charAt(position);

        if (next == '(' || next == '[' || next == '{') 
        {
            // Process opening bracket, write your code here
            Bracket temp = new Bracket(next,position);
            opening_brackets_stack.push(temp);
        }

        if (next == ')' || next == ']' || next == '}') 
        {
            // Process closing bracket, write your code here
            try{
                Bracket item = opening_brackets_stack.pop();
                if(!item.Match(next)) 
                {  //not match
                    System.out.println(position+1);  
                    return;
                }
            }   
            catch(EmptyStackException e){}
        }
    }
    // Printing answer, write your code here
    try{
        if(opening_brackets_stack.isEmpty()) 
        {
          System.out.println("Success");
        }
        else {
            Bracket item = opening_brackets_stack.pop();
            //print position of first unmatched opening bracket
            System.out.println(item.position+1);
        }
    }
    catch (EmptyStackException e){}

}

在括号位于最后位置的“}”、“()}”等情况下,我会得到错误的答案。 对于上述情况,我应该分别得到答案“1”,“3”,但我得到“成功”。 在所有其他情况下,它都可以正常工作。 我该怎么办?

【问题讨论】:

  • 你不应该有空的 catch 块。如果发生 EmptyStackException 之一,至少打印堆栈跟踪。如果你只是忽略它们,你现在怎么知道你的代码是否只是抛出异常。
  • “我应该怎么做?” 调试你的代码。不要要求我们为您进行调试。 What is a debugger and how can it help me diagnose problems?.

标签: java exception stack


【解决方案1】:

对于像"}" 这样的字符串,您的代码会尝试从堆栈中弹出一个左大括号。但是堆栈是空的,所以你得到一个EmptyStackException,并且控制权被转移到你的异常处理程序。什么都不做。

与其试图捕获异常,不如检查堆栈是否为空。如果是,那么你知道你有太多的右大括号。对待它就像对待来自item.Match 的虚假回报一样。

【讨论】:

    猜你喜欢
    • 2015-02-16
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多