Given a List of words, return the words that can be typed using letters ofalphabeton only one row's of American keyboard like the image below.
Example 1:
Input:
["Hello", "Alaska", "Dad", "Peace"]
Output:
["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
Subscribeto see which companies asked this question.
Hide Tags
public class Solution {
public String[] findWords(String[] words) {
List<String> result = new ArrayList<String>();
Map<Character,Integer> charMap = new HashMap<Character, Integer>();
String[] keyboard = {"qwertyuiop","asdfghjkl","zxcvbnm"};
for(int i=0;i<keyboard.length;i++){
String key = keyboard[i];
for(char c : key.toCharArray()){
charMap.put(c, i);
}
}
for (int i = 0; i < words.length; i++) {
String word = words[i];
int index = charMap.get(word.toLowerCase().charAt(0));
for(int j=1;j<word.length();j++){
if(charMap.get(word.toLowerCase().charAt(j)) != index){
index = -1;
break;
}
}
if(index != -1){
result.add(word);
}
}
return result.toArray(new String[0]);
}
}