Given an array of strings, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
"qwertyuiop"
."asdfghjkl"
."zxcvbnm"
.Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
import java.util.*;
public class Solution {
public String[] findWords(String[] words) {
// Define the sets for each keyboard row
Set<Character> row1 = new HashSet<>(Arrays.asList(
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'));
Set<Character> row2 = new HashSet<>(Arrays.asList(
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'));
Set<Character> row3 = new HashSet<>(Arrays.asList(
'z', 'x', 'c', 'v', 'b', 'n', 'm'));
List<String> result = new ArrayList<>();
for (String word : words) {
if (canBeTypedWithOneRow(word.toLowerCase(), row1) ||
canBeTypedWithOneRow(word.toLowerCase(), row2) ||
canBeTypedWithOneRow(word.toLowerCase(), row3)) {
result.add(word);
}
}
return result.toArray(new String[0]);
}
private boolean canBeTypedWithOneRow(String word, Set<Character> row) {
for (char c : word.toCharArray()) {
if (!row.contains(c)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] input = {"Hello", "Alaska", "Dad", "Peace"};
String[] output = solution.findWords(input);
System.out.println(Arrays.toString(output)); // Should print ["Alaska", "Dad"]
}
}
Therefore, the solution is efficient and should work well within typical input size constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?