본문 바로가기

열정가득한 개발자의 이야기/Javascript Algorithm

500. Keyboard Row (javascript)

반응형
 

 
Hi, today I worked on a problem that seems to be related to Hash Maps.
To summarize:
there are three layers, so I tried using a Map like ["a", "1"], ["b", "2"].
However, it didn’t work properly.
To solve the problem in my own way, I used a String and compared values directly.
Yeah... the code ended up being really long, and the efficiency isn’t great.
But I think solving the problem is more important for now.
Anyway, this is my code.
 
var findWords = function(words) {
let y = words.map((i) => i.toLowerCase())
let t = ""
let result = []
let a = "qwertyuiopasdfghjklzxcvbnm"
for(let i = 0; i< y.length; i++){
     for(let j = 0; j < y[i].length; j++){
         let x = a.indexOf(y[i][j])
         if(x < 10 ){
        t += "1"
    }else if(x < 19 ){
     t+="2"
     }else {
      t+= "3"
   }
}
   result.push(t)
    t = ""
  }
let fi = []
     for(let i = 0; i< result.length; i++){
          let s = true
        for(let j = 0; j < result[i].length - 1; j++){
              if(result[i][j] !== result[i][j+1]){
                  s = false
                  break
                }
                }
              if(s){
                 fi.push(words[i])
              }
        }
          return fi
    };

 

It works properly, but I know there’s a more efficient way to solve this.
Now, I’ll go study better solutions to improve my approach.

반응형