Keyboard Row
Description
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
Example:
Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
Solution(javascript)
/**
* @param {string[]} words
* @return {string[]}
*/
const findWords = (words) => {
const firstRow = 'qwertyuiop'
const secondRow = 'asdfghjkl'
const thirdRow = 'zxcvbnm'
const dict = {}
const generateDict = (d, row, num) => {
for (c of row) {
d[c] = num
}
}
generateDict(dict, firstRow, 1)
generateDict(dict, secondRow, 2)
generateDict(dict, thirdRow, 3)
const isSameRow = (word = '') => {
word = word.toLowerCase()
let previous = null
for (c of word) {
if (previous && dict[c] !== previous) {
return false
}
previous = dict[c]
}
return previous
}
return words.filter(isSameRow)
}