Balanced Brackets

  • + 0 comments

    Java 15

    var squareOpen = false;
    var curlyOpen = false;
    var parenthesisOpen = false;
    
    Queue<Character> brackets = new LinkedList<>();
    Stack<Character> expectedClosures = new Stack<>();
    for (var c : s.toCharArray()) {
    	brackets.add(c);
    }
    
    while (!brackets.isEmpty()) {
    	var ele = brackets.poll();
    	try {
    		switch (ele) {
    			case '[': squareOpen = true; expectedClosures.add(']'); break;
    			case '(': parenthesisOpen = true; expectedClosures.add(')'); break;
    			case '{': curlyOpen = true; expectedClosures.add('}'); break;
    			case ']': squareOpen = false; if (expectedClosures.pop() != ele) return "NO"; break;
    			case ')': parenthesisOpen = false; if (expectedClosures.pop() != ele) return "NO"; break;
    			case '}': curlyOpen = false; if (expectedClosures.pop() != ele) return "NO";
    		}
    	} catch (EmptyStackException ex) {
    		return "NO";
    	}
    }
    return !squareOpen && !parenthesisOpen && !curlyOpen ? "YES" : "NO";