Balanced Brackets

Balanced Brackets

by Hilarius Doren

HTML

<p>
Write function to find Balanced Brackets. Brackets is considered to be any one of the following characters: (,),{,},[, or ].
</p>
<p>
Check matched pairs between opening barcket and close bracket with return string YES or NO 
</p>

JavaScript

let isMatchingBrackets = function (str) {
    let stack = [];
    let map = {
        '(': ')',
        '[': ']',
        '{': '}'
    }

    for (let i = 0; i < str.length; i++) {

        // If character is an opening brace add it to a stack
        if (str[i] === '(' || str[i] === '{' || str[i] === '[' ) {
            stack.push(str[i]);
        }
        //  If that character is a closing brace, pop from the stack, which will also reduce the length of the stack each time a closing bracket is encountered.
        else {
            let last = stack.pop();

            //If the popped element from the stack, which is the last opening brace doesn’t match the corresponding closing brace in the map, then return false
            if (str[i] !== map[last]) {return 'NO'};
        }
    }
    // By the completion of the for loop after checking all the brackets of the str, at the end, if the stack is not empty then fail
        if (stack.length !== 0) {return 'NO'};

    return 'YES';
}

console.log(isMatchingBrackets("(){}")); // returns YES
console.log(isMatchingBrackets("[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]")); // returns YES
console.log(isMatchingBrackets("({(()))}}"));  // returns NO