Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2771
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  猫巷女王i
    2020-11-27 12:08

    This code is easier to understand:

    public static boolean CheckParentesis(String str)
    {
        if (str.isEmpty())
            return true;
    
        Stack stack = new Stack();
        for (int i = 0; i < str.length(); i++)
        {
            char current = str.charAt(i);
            if (current == '{' || current == '(' || current == '[')
            {
                stack.push(current);
            }
    
    
            if (current == '}' || current == ')' || current == ']')
            {
                if (stack.isEmpty())
                    return false;
    
                char last = stack.peek();
                if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                    stack.pop();
                else 
                    return false;
            }
    
        }
    
        return stack.isEmpty();
    }
    

提交回复
热议问题