[leetcode] problem 500 – keyboard row

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.

exFfUK.png

Example

Input: [“Hello”, “Alaska”, “Dad”, “Peace”]

Output: [“Alaska”, “Dad”]

Note

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private String[] rows = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};

public String[] findWords(String[] words) {
List<String> result = new ArrayList<>();

for (String word : words) {
for (String row : rows) {
if (check(word.toLowerCase(), row)) {
result.add(word);
break;
}
}
}

return result.toArray(new String[result.size()]);
}

private boolean (String word, String row) {
for (char ch : word.toCharArray()) {
if (row.indexOf(ch) == -1)
return false;
}

return true;
}