isValid(). Javascript Solution. Runtime: 102ms


  • 0

    A bit elaborate. Runtime: 102 ms

    var isValid = function(s) {
        if (s) {
            var stack = [];
            for(var i = 0; i < s.length; i++) {
                if (isValidOpeningParenthesis(s[i])) {
                    stack.push(s[i])
                } else if (isValidClosingParenthesis(s[i])) {
                    if (isValidParenthesis(s[i], stack[stack.length - 1])) {
                        stack.pop();
                    } else {
                        stack.push(s[i]);
                    }
                }
            }
            return stack.length === 0;
        }
        return false;
    };
    
    function isValidClosingParenthesis(p) {
        return p == ")" || p == "]" || p == "}";
    }
    
    function isValidOpeningParenthesis(p) {
        return p == "(" || p == "[" || p == "{";
    }
    
    function isValidParenthesis(s, p) {
        var validClosingParenthesis = {
            ")": "(",
            "}": "{",
            "]": "["
        };
        return p == validClosingParenthesis[s];
    }
    

Log in to reply
 

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