在代码的Chech括号中的测试用例中获得错误的输出

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”,但我却获得“成功”。 在所有其他情况下,它都可以正常工作。 我该怎么办?

评论