Balanced Brackets

  • + 0 comments

    js answer using a map for checking correlation:

    function isBalanced(s) {
        // Write your code here
        let openStack = new Array();
        let idx = 0;
        let valid = true;
        let correlationMap = new Map([
            [')', '('],
            [']', '['],
            ['}', '{'],
        ]);
        while(valid && idx<s.length){
            if(correlationMap.has(s[idx]) && (correlationMap.get(s[idx]) != openStack.pop())){
                valid = false;
            }else if(!correlationMap.has(s[idx])){
                openStack.push(s[idx]);
            }
            idx++;
        }
        if(openStack.length > 0) valid = false;
        return (valid)?('YES'):('NO');
    }