Stacks: Balanced Brackets

  • + 0 comments

    This is my JavaScript version of this solution:

    function is_balanced(expression) {
        const stack = []; 
        
        const brackets = {
            "{": "}",
            "[": "]",
            "(": ")"
        }; 
        
        for (let i = 0; i < expression.length; i++) {
            const b = expression[i];
            if (brackets[b] !== undefined) stack.push(brackets[b]); // it's an opening bracket, so push the corresponding closing one into the stack
            else {
                if (stack.length === 0 || b !== stack[stack.length-1]) return false;
                stack.pop();
            }
        }
        return stack.length === 0;
    }
    

    If you write a simple hash map like the brackets object, you don't need to explicitly check if a given bracket is a closing one by using ifs. Just see if the hash map has the desired key (in this case an opening bracket). If so, push the value into the stack (in this case a closing bracket). The rest is pretty much the same.