martes, 4 de octubre de 2016

You're working with an intern that keeps coming to you with JavaScript code that won't run because the braces, brackets, and parentheses are off. To save you both some time, you decide to write a braces/brackets/parentheses validator.
Let's say:
  • '(', '{', '[' are called "openers."
  • ')', '}', ']' are called "closers."
Write an efficient function that tells us whether or not an input string's openers and closers are properly nested.
Examples:
  • "{ [ ] ( ) }" should return true
  • "{ [ ( ] ) }" should return false
  • "{ [ }" should return false
ref: https://www.interviewcake.com/question/javascript/bracket-validator



  
var openers = ['(', '{', '['];
var closers = [')', '}', ']'];
function braces_brackets_parentheses_validator(code) {
    var stack = [];
    for(var i in code){
        index = openers.indexOf(code[i]);
        if(index >= 0){
            //console.log('push:'+code[i]);
            stack.push(code[i]);
        }else{
            index = closers.indexOf(code[i]);
            if(index >= 0){
                if(stack[stack.length-1] != openers[index]){
                    console.log('opener:"'+stack[stack.length -1]+'" unexpected closer:"'+closers[index]+'" at index:'+i);
                    return false;
                }
                //console.log('pop:'+stack[stack.length -1]);
                stack.pop();
            }
        }
    }
        
    return true;
}

// run your function through some test cases here
// remember: debugging is half the battle!
console.log(braces_brackets_parentheses_validator('{ [ ] ( ) }'));
console.log(braces_brackets_parentheses_validator('{ [ ( ] ) }'));
console.log(braces_brackets_parentheses_validator('{ [ }'));

  
 

No hay comentarios:

Publicar un comentario