版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82793665
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.
样例
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
注意事项
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
解题思路:
用HashMap存储键盘,key为字母,value为对应的行号。然后依次判断是否在同一行即可。
public class Solution {
/**
* @param words: a list of strings
* @return: return a list of strings
*/
public String[] findWords(String[] words) {
// write your code here
Map<Character, Integer> map = new HashMap<Character, Integer>();
initMap(map);
List<String> list = new ArrayList<>();
for(String word : words){
String temp = word.toLowerCase(); //全部转换为小写字母
int line = map.get(temp.charAt(0));//首字母所处的行号
boolean flag = true;
for(int i=1 ; i<temp.length() ; i++){
if(map.get(temp.charAt(i)) != line){
flag = false;
break;
}
}
if(flag)
list.add(word);
}
return list.toArray(new String[0]);
}
private void initMap(Map<Character, Integer> map){
map.put('q', 1);
map.put('w', 1);
map.put('e', 1);
map.put('r', 1);
map.put('t', 1);
map.put('y', 1);
map.put('u', 1);
map.put('i', 1);
map.put('o', 1);
map.put('p', 1);
map.put('a', 2);
map.put('s', 2);
map.put('d', 2);
map.put('f', 2);
map.put('g', 2);
map.put('h', 2);
map.put('j', 2);
map.put('k', 2);
map.put('l', 2);
map.put('z', 3);
map.put('x', 3);
map.put('c', 3);
map.put('v', 3);
map.put('b', 3);
map.put('n', 3);
map.put('m', 3);
}
}