Leetcode 20. Valid Parentheses - javascript




/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    var stack = [];
  
    for(var i = 0; i < s.length; i++){
        var c = s.charAt(i);
        
        if(c == "(" || c == "[" || c == "{"){
            stack.push(c);
        } else {
            if(stack.length === 0) {
                return false;
            } 
          
            var oldC = stack.pop();
            if(oldC == '(' && c != ')'){
                return false;
            } else if(oldC == '[' && c != ']'){
                return false;
            } else if(oldC == '{' && c != '}'){
                return false;
            }
        }
    }
    
    return stack.length === 0;
};


你可能感兴趣的:(技术文章)