-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyboardRow.java
46 lines (40 loc) · 1.67 KB
/
KeyboardRow.java
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
public class Solution {
public String[] findWords(String[] words) {
if(words == null || words.length == 0){
return new String[0];
}
Set<Character> firstRow = new HashSet<>(Arrays.asList('Q', 'W', 'E','R','T','Y','U','I','O','P'));
Set<Character> secondRow = new HashSet<>(Arrays.asList('A', 'S', 'D','F','G','H','J','K','L'));
Set<Character> thirdRow = new HashSet<>(Arrays.asList('Z', 'X', 'C','V','B','N','M'));
List<String> resultWords = new ArrayList<>();
for(String word: words){
Set<Character> selectedRow = chooseARow(word.charAt(0), firstRow, secondRow, thirdRow);
if(checkIfBelongsTo(selectedRow, word)){
resultWords.add(word);
}
}
return resultWords.stream()
.toArray(size -> new String[size]);
}
public Set<Character> chooseARow(Character c, Set<Character> firstRow, Set<Character> secondRow, Set<Character> thirdRow){
Set<Character> selectedRow = null;
if(firstRow.contains(Character.toUpperCase(c))){
selectedRow = firstRow;
}
if(secondRow.contains(Character.toUpperCase(c))){
selectedRow = secondRow;
}
if(thirdRow.contains(Character.toUpperCase(c))){
selectedRow = thirdRow;
}
return selectedRow;
}
public boolean checkIfBelongsTo(Set<Character> selectedRow, String word){
for(int i=0; i<word.length(); i++){
if(!selectedRow.contains(Character.toUpperCase(word.charAt(i)))){
return false;
}
}
return true;
}
}