Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2768
你的背包
你的背包 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条回答
  •  悲哀的现实
    2020-11-27 12:07

    Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.

    This code, modified slightly from yours, seems to work properly:

    public static boolean isParenthesisMatch(String str) {
        if (str.charAt(0) == '{')
            return false;
    
        Stack stack = new Stack();
    
        char c;
        for(int i=0; i < str.length(); i++) {
            c = str.charAt(i);
    
            if(c == '(')
                stack.push(c);
            else if(c == '{')
                stack.push(c);
            else if(c == ')')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '(')
                    stack.pop();
                else
                    return false;
            else if(c == '}')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '{')
                    stack.pop();
                else
                    return false;
        }
        return stack.empty();
    }
    

提交回复
热议问题