题目:
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.
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.
题意:给定一系列的字符串,找出那些字符串是由键盘的同一行上的字母组成的。
思路一:键盘上共有三行字母,每一行字母都映射到一个map中:map1、map2、map3。对每一个字符串,根据字符串的首字母确定在键盘的哪一行,随后逐一判断后面的字符是否属于同一行。
代码:
class Solution {
public static String[] findWords(String[] words) {
char[] c1 = {'q','w','e','r','t','y','u','i','o','p'};
char[] c2 = {'a','s','d','f','g','h','j','k','l'};
char[] c3 = {'z','x','c','v','b','n','m'};
Map<Character, Integer> map1 = new HashMap<Character, Integer>();
Map<Character, Integer> map2 = new HashMap<Character, Integer>();
Map<Character, Integer> map3 = new HashMap<Character, Integer>();
for(int i=0;i<c1.length;i++)
map1.put(c1[i],i);
for(int i=0;i<c2.length;i++)
map2.put(c2[i],i);
for(int i=0;i<c3.length;i++)
map3.put(c3[i],i);
List<String> ss = new ArrayList<String>();
for(String word:words){
String newWord = word.toLowerCase();
char[] cs = newWord.toCharArray();
char[] cs2 = word.toCharArray();
if(map1.containsKey(cs[0])){
String s = "";
for(int i=0;i<cs.length;i++){
if(!map1.containsKey(cs[i]))
break;
else
s = s+cs2[i];
if(i == cs.length-1)
ss.add(s);
}
}else if(map2.containsKey(cs[0])){
String s = "";
for(int i=0;i<cs.length;i++){
if(!map2.containsKey(cs[i]))
break;
else
s = s+cs2[i];
if(i == cs.length-1)
ss.add(s);
}
}else{
String s = "";
for(int i=0;i<cs.length;i++){
if(!map3.containsKey(cs[i]))
break;
else
s = s+cs2[i];
if(i == cs.length-1)
ss.add(s);
}
}
}
return (String[])ss.toArray(new String[ss.size()]);
}
}
思路二:建立一个map,把键盘上的每一行字母和自己所在的行数映射起来。即qwertyuiop,每个字母都映射为0,asdfghjkl每个字母都映射成1,zxcvbnm每个字母都映射成2。对于需要判定的字符串,首先确定首字符所在的行数,并逐一判断后续字符是否与首字符属于同一行。若中间有不一致的,立马结束,否则,该字符串符合要求。
代码:
class Solution {
public static String[] findWords(String[] words) {
String[] keyboardWords = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i=0;i<keyboardWords.length;i++)
for(char c:keyboardWords[i].toCharArray())
map.put(c,i);
List<String> finalWords = new ArrayList<String>();
for(String word: words){
char first = word.toUpperCase().charAt(0);
int index = map.get(first);
for(char c: word.toUpperCase().toCharArray()){
if(map.get(c)!=index){
index = -1;
break;
}
}
if(index!=-1)
finalWords.add(word);
}
return (String[])finalWords.toArray(new String[finalWords.size()]);
}
}
思路一的执行时间为4ms,思路二的执行时间为6ms。