Title:Keyboard Row 500
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/keyboard-row/
1. 采用map
时间复杂度:O(n^2),嵌套循环。
空间复杂度:O(n),申请Map、List。
/**
* 把键盘中的字母和其所在行数放到map
* @param words
* @return
*/
public static String[] findWords(String[] words) {
String[] str = {"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"};
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length; i++) {
for (char c : str[i].toCharArray()) {
map.put(c, i);
}
}
List<String> list = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
int firstIndex = map.get(words[i].toUpperCase().toCharArray()[0]);
for (char c : words[i].toUpperCase().toCharArray()) {
if (map.get(c) != firstIndex) {
firstIndex = -1;
break;
}
}
if (firstIndex != -1) {
list.add(words[i]);
}
}
return list.toArray(new String[list.size()]);
}