Parenthesis/Brackets Matching using Stack algorithm

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

    public static boolean isBalanced(String s) {
        Map openClosePair = new HashMap();
        openClosePair.put('(', ')');
        openClosePair.put('{', '}');
        openClosePair.put('[', ']'); 
    
        Stack stack = new Stack();
        for (int i = 0; i < s.length(); i++) {
    
            if (openClosePair.containsKey(s.charAt(i))) {
                stack.push(s.charAt(i));
    
            } else if ( openClosePair.containsValue(s.charAt(i))) {
                if (stack.isEmpty())
                    return false;
                if (openClosePair.get(stack.pop()) != s.charAt(i))
                    return false;
            }
    
            // ignore all other characters
    
        }
        return stack.isEmpty();
    }
    

提交回复
热议问题