Balanced Brackets

  • + 0 comments

    JS

    function isBalanced(string) {
        const pairs = new Map([[")", "("], ["}", "{"], ["]", "["]]);
        const brackets = [];
        let balanced = true;
        for (let bracket of string) {
            if (pairs.has(bracket)) {
                if (brackets.pop() != pairs.get(bracket)) {
                    balanced = false;
                    break;
                }
            }
            else {
                brackets.push(bracket);
            }
        }
        return (balanced && brackets.length == 0) ? "YES" : "NO";
    }