Balanced.java

Download
1public class Balanced {2    public static boolean isBalanced(String str) {3        Stack<Character> s = new LLStack<>();4 5        for (int i = 0; i < str.length(); i++) {6            char ch = str.charAt(i);7 8            // if the char is an opening, push onto stack9            if (ch == '(' || ch == '{' || ch == '[') {10                s.push(ch);11 12            } else if (ch == ')' || ch == '}' || ch == ']') {13                if (s.isEmpty()) {14                    return false;15                }16 17                char stackChar = s.pop();       // open18 19                if (20                    ch == ')' && stackChar != '(' ||21                    ch == '}' && stackChar != '{' ||22                    ch == ']' && stackChar != '['23                ) {24                    return false;25                }26            }27 28        }29 30        if (!s.isEmpty()) {31            // more opens than closes32            return false;33        }34 35        // if there's time: the indexOf() trick36 37        return true;38    }39 40    public static void main(String[] args) {41        System.out.println("balanced inputs:");42        System.out.println("{{{}}} -> " + isBalanced("{{{}}}"));43        System.out.println("{{{}{}{}}} -> " + isBalanced("{{{}{}{}}}"));44 45        System.out.println("NOT balanced inputs:");46        System.out.println("{([}]) -> " + isBalanced("{([}])"));47        System.out.println("(((( -> " + isBalanced("(((("));48        System.out.println(")))) -> " + isBalanced("))))"));49    }50}