05 August 2008
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:
1
2
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
检查一个字符串数组里面的所有字符串,返回一些字符串,这些字符串只用键盘中的一行就可以写出来。可以用regex或者hashmap。把在同row的char标记成同index存在HashMap中;然后判定word中的每一个char是否有相同的index;Time Complexity: O(n), n是words中每个word的char总和.
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
26
27
28
29
30
31
class Solution {
public String[] findWords(String[] words) {
if (words == null || words.length == 0) {
return words;
}
String[] keyboard = {"qwertyuiop","asdfghjkl","zxcvbnm"};
HashMap<Character, Integer> hm = new HashMap<>();
for (int i = 0; i < keyboard.length; i++) {
for (char c : keyboard[i].toCharArray()) {
hm.put(c, i);//每一列的i不一样0,1,2
}
}
List<String> result = new ArrayList<>();
for (String word : words) {
if (word == "") {
continue;
}
int index = hm.get(word.toLowerCase().charAt(0));//查一下第一个字符的index
//检查字符串里面所有字符的index
for (char c : word.toLowerCase().toCharArray()) {
if (index != hm.get(c)) {//如果有字符的index和第一个字符不相同
index = -1;
}
}
if (index != -1) {
result.add(word);
}
}
return result.toArray(new String[0]);//new String[0]确定是字符串数组
}
}