Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2724
你的背包
你的背包 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:03

    You're doing some extra checks that aren't needed. Doesn't make any diff to functionality, but a cleaner way to write your code would be:

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

    There is no reason to peek at a paranthesis before removing it from the stack. I'd also consider wrapping instruction blocks in parantheses to improve readability.

提交回复
热议问题