Balanced Brackets

  • + 1 comment

    My Java solution:

    public static String isBalanced(String s) {
            
            Stack<Character> stack = new Stack<>();
            HashMap<Character, Character> map = new HashMap<>();
            map.put(')', '(');
            map.put(']', '[');
            map.put('}', '{');
            
            // \ ({}) \     \ )({}) \
            for (char c : s.toCharArray()) {
                if (map.containsKey(c)) {
                    if (!stack.isEmpty() && stack.peek() == map.get(c)) {
                        stack.pop();
                    } else {
                        return "NO";
                    }
                } else {
                    stack.push(c);
                }
            }
            
            return (stack.isEmpty()) ? "YES" : "NO";
        }