Description
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.
解法1
public class Solution {
public String[] findWords(String[] words) {
List<String> oneRowWords = new ArrayList<String>();
String[] keyboard = {"qwertyuiop","asdfghjkl","zxcvbnm"};
for(String word : words) {
String realWord = word;
word = word.toLowerCase();//每个字母变为小写
char[] strBit = word.toCharArray();
int count = 0;
for(char ch : strBit) {
if(keyboard[0].indexOf(strBit[0]) != -1) {//第一个字母在第一排
if(keyboard[0].indexOf(ch) == -1) {//其他字母必须也在第一排 否则跳过
break;
}
}else if(keyboard[1].indexOf(strBit[0]) != -1) {//第一个字母在第二排
if(keyboard[1].indexOf(ch) == -1) {
break;
}
}else if(keyboard[2].indexOf(strBit[0]) != -1) {//第一个字母在第三排
if(keyboard[2].indexOf(ch) == -1) {
break;
}
}
count ++;
}
if(count == strBit.length) {
oneRowWords.add(realWord);
}
}
String[] oneRowWordsArray = new String[oneRowWords.size()];
for(int i=0; i<oneRowWords.size(); i++){
oneRowWordsArray[i] = oneRowWords.get(i);
}
return oneRowWordsArray;
}
}
解法2
把键盘中的字母和其所在行数放到map。
public static String[] findWords2(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);
}
}
int index = 0;
List<String> res = new ArrayList<>();
for(String word : words) {
if (word.equals("")) continue;
index = map.get(word.toUpperCase().toCharArray()[0]);
for(char c : word.toUpperCase().toCharArray()) {
if(map.get(c) != index) {
index = -1;//不用设置flag 直接把index设为-1即可
break;
}
}
if(index != -1) res.add(word);
}
return res.toArray(new String[res.size()]);
}