-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyboardRow.java
More file actions
63 lines (55 loc) · 1.85 KB
/
KeyboardRow.java
File metadata and controls
63 lines (55 loc) · 1.85 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package LeetCodeOJ;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* leetcode 500 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.
*
* @author fqx
*
*/
public class KeyboardRow {
public String[] findWords(String[] words) {
//prepare the map
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("qwertyuiop", 0);
map.put("asdfghjkl", 1);
map.put("zxcvbnm", 2);
ArrayList<String> arr = new ArrayList<String>();
//store the result
for (int i = 0; i < words.length; i++) {
if(isSameLayer(words[i], map)){
arr.add(words[i]);
}
}
return arr.toArray(new String[arr.size()]);
}
public boolean isSameLayer(String str, HashMap<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
int i = 0;
//search each character of the str in these map.entrySet()
for (; i < str.length(); i++) {
if (entry.getKey().indexOf(Character.toLowerCase(str.charAt(i))) != -1) {
continue;
}else{
break;
}
}
// only if every character of the str exist in the same key in map
//namely i == str.length(), find it.
if(i == str.length()){
return true;
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words = { "Hello", "Alaska", "Dad", "Peace" };
String [] result = new KeyboardRow().findWords(words);
System.out.println(Arrays.toString(result));
}
}