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.
1
2
3
4
| Example:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
|
Java Solution:
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
64
65
66
67
68
69
| private Set<Character> firstSet = new HashSet<>();
private Set<Character> secondSet = new HashSet<>();
private Set<Character> thirdSet = new HashSet<>();
String firstRow = "qwertyuiop";
String secondRow = "asdfghjkl";
String thirdRow = "zxcvbnm";
public void initSets(){
for (char mChar:firstRow.toCharArray()) {
firstSet.add(mChar);
firstSet.add(Character.toUpperCase(mChar));
}
for (char mChar:secondRow.toCharArray()) {
secondSet.add(mChar);
secondSet.add(Character.toUpperCase(mChar));
}
for (char mChar:thirdRow.toCharArray()) {
thirdSet.add(mChar);
thirdSet.add(Character.toUpperCase(mChar));
}
}
Solution(){
initSets();
}
public String[] findWords(String[] words) {
List<String> ret = new LinkedList<>();
for(String str: words){
int []whichRows = {0,0,0};
for(char mChar:str.toCharArray()){
if(isFromFirstSets(mChar)){
whichRows[0] = 1;
}
else if(isFromSecondSets(mChar)){
whichRows[1] = 1;
}
else if (isFromThirdSets(mChar)){
whichRows[2] = 1;
}
}
int sum = 0;
for(int ele:whichRows){
sum += ele;
}
if(sum == 1){
ret.add(str);
}
}
String []retStr = new String[ret.size()];
ret.toArray(retStr);
return retStr;
}
private Boolean isFromFirstSets(char mChar){
return firstSet.contains(mChar);
}
private Boolean isFromSecondSets(char mChar){
return secondSet.contains(mChar);
}
private Boolean isFromThirdSets(char mChar){
return thirdSet.contains(mChar);
}
}
|