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 1:
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 1
/**
* @param {string[]} words
* @return {string[]}
*/
var findWords = function(words) {
"use strict";
let rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"];
return words.filter((word) => {
word = word.toLowerCase();
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < word.length; j++) {
if (!rows[i].includes(word[j])) {
if (i === rows.length-1) {
return false;
}
break;
} else {
if (j === word.length-1) {
return true;
}
}
}
}
});
};
Solution 2
/**
* Solved with regular expression
* @param {string[]} words
* @return {string[]}
*/
var findWords = function(words) {
"use strict";
return words.filter((word) => {
word = word.toLowerCase();
return word.replace(/[qwertyuiop]/g, "").length === 0 ||
word.replace(/[asdfghjkl]/g, "").length === 0 ||
word.replace(/[zxcvbnm]/g, "").length === 0;
});
};