JavaScript Solution


  • 0
    S

    Hi, I would like to improve my coding skill and my logic, please feel free to correct my algorithm. Thank you so much

    /**
     * @param {string[]} words
     * @return {string[]}
     */
    var findWords = function(words) {
        var returnArray = [];
        for(var i = 0; i < words.length; i++){
            if(checkWord(words[i])){
                returnArray.push(words[i]);
            }
        }
        return returnArray;
    };
    
    function checkWord(word){
        var array = wordToArray(word);
        var index = encode(array[0]);
        console.log(index)
        for(var i = 1; i < array.length; i++){
            if(encode(array[i]) !== index){
    
                return false
            }
        }
        return true;
    }
    
    function wordToArray(word){
        var array = []
        for(var i = 0; i < word.length; i++){
            array.push(word[i]);
        }
        return array;
    }
    
    function encode(letter){
        console.log("input ---" + letter)
        letter = letter.toLowerCase();
        var a = [];
        a['a'] = 1
        a['b'] = 2
        a['c'] = 2
        a['d'] = 1
        a['e'] = 0
        a['f'] = 1
        a['g'] = 1
        a['h'] = 1
        a['i'] = 0
        a['j'] = 1
        a['k'] = 1
        a['l'] = 1
        a['m'] = 2
        a['n'] = 2
        a['o'] = 0
        a['p'] = 0
        a['q'] = 0
        a['r'] = 0
        a['s'] = 1
        a['t'] = 0
        a['u'] = 0
        a['v'] = 2
        a['w'] = 0
        a['x'] = 2
        a['y'] = 0
        a['z'] = 2
        console.log("output ---" + a[letter])
        return a[letter];
    }
    

  • 0
    var findWords = function(words) {
      
    var rows = [['q','w','e','r','t','y','u','i','o','p'], ['a','s','d','f','g','h','j','k','l'],['z','x','c','v','b','n','m']];
         var newA = [] ; 
         for (var i=0 ; i<words.length; i++){
    
              if (checkRow( words[i],rows)== true )
              newA.push (words[i]); 
             
         };
         return newA;
         
    };
    
    
    var checkRow = function (w,rows){
        var wA = w.toLowerCase().split('');   var firstL = wA[0] ;  var inRow = 0 ;  
        for (var i=0 ; i<rows.length;i++){  
              if (rows[i].indexOf(firstL)!=-1) { inRow=i ; } ;  
              
        }; 
    
        for (var i=0 ; i<wA.length;i++){
             if ( rows[inRow].indexOf (wA[i]) == -1 ) return false ;
        }
        
        return true ; 
        
        
    }
    

Log in to reply
 

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