O(n) solution in javascript of valid parenthesis


  • 0
    S
     * @param {string} s
     * @return {boolean}
     * {[ ]}
     */
    var isValid = function(s) {
        var arrStack = []; //stack
        var open = ["[", "{", "("];
        var close = ["]", "}", ")"];
        for (var i=0;i< s.length; i++) {
            if(open.indexOf(s[i]) !== -1) {
                arrStack.push(s[i]);
            }
            else {
                var x = arrStack.pop();
                var idx = open.indexOf(x);
                if (close[idx] !== s[i]) {
                    return false;
                }
            }
        }
        if(arrStack.length === 0) {
            return true;
        } 
        return false;
    };
    

Log in to reply
 

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