Simple JavaScript Solution


  • 0
    Z

    I used a map with the close parenthesis as a key and the open as the value. I suppose this adds a step then over a switch statement that checks each character for its complement, but it demonstrates how we can use a data structure to organize our rules. Otherwise, my solution seems to look similar to others in that I'm using a stack to push my open parenthesis onto, and am popping the open parens off the stack when we the appropriate close paren resolves it.

    /**
     * @param {string} s
     * @return {boolean}
     */
    var isValid = function(s) {
        var arr = [];
        var myMap = new Map();
        //Map of complements
        myMap.set(')', '(');
        myMap.set(']', '[');
        myMap.set('}', '{');
        
        for(var i = 0; i < s.length; i++){
            if(s[i] === ')' || s[i] === ']' || s[i] === '}'){
                var complement = myMap.get(s[i]);
                //check if top thing on the stack 
                if(arr.length && arr[arr.length - 1] === complement) {
                    arr.pop();  
                } else {
                   return false;
                }
            } else if(s[i] === '(' || s[i] === '[' || s[i] === '{'){
                    arr.push(s[i]);
            }
        }
        if(arr.length > 0){
            return false;
        } else {
            return true;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.