• + 4 comments

    Couple of suggestions for improvement.


    - Do not use the Stack class, since it has been deprecated for a while. Instead use the ArrayDeque class which is meant to replace it. Even the JDK documentation suggests the same:

    A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:
    
       Deque<Integer> stack = new ArrayDeque<Integer>();
    


    - switch-case blocks are generally more readable, and at the same time easily optimized by compiler and JVM (at runtime).


    - You can combine the peek and the pop into a single operation. When you see a closing bracket, if either the stack is empty or the top of the stack (after pop) does not match you fail right away. If it matches, the pop is still applicable, and you continue with your iteration. Look at this code snippet (I'm pasting only the helper method)

    private static final Deque<Character> sQueue = new ArrayDeque<>();
    
    private static boolean isBalanced(String str) {
            sQueue.clear();
            int len = str.length();
            boolean failed = false;
            for (int ix = 0; !failed && ix < len; ++ix) {
                char currChar = str.charAt(ix);
                switch (currChar) {
                    case '(':
                    case '[':
                    case '{':
                        sQueue.addFirst(currChar);
                        break;
                    case ']':
                        failed = sQueue.size() == 0 || (sQueue.removeFirst() != '[');
                        break;
                    case ')':
                        failed = sQueue.size() == 0 || (sQueue.removeFirst() != '(');
                        break;
                    case '}':
                        failed = sQueue.size() == 0 || (sQueue.removeFirst() != '{');
                        break;
                    default:
                        failed = true;
                        break;
                }
            }
            failed |= (sQueue.size() != 0);
            return !failed;
        }