Parenthesis/Brackets Matching using Stack algorithm

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

    public static boolean isValidExpression(String expression) {
        Map openClosePair = new HashMap();
        openClosePair.put(')', '(');
        openClosePair.put('}', '{');
        openClosePair.put(']', '[');        
        Stack stack = new Stack();
        for(char ch : expression.toCharArray()) {
            if(openClosePair.containsKey(ch)) {
                if(stack.pop() != openClosePair.get(ch)) {
                    return false;
                }
            } else if(openClosePair.values().contains(ch)) {
                stack.push(ch); 
            }
        }
        return stack.isEmpty();
    }
    

提交回复
热议问题