Keyboard Row
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
the first row consists of the characters "qwertyuiop",
the second row consists of the characters "asdfghjkl", and
the third row consists of the characters "zxcvbnm".
Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Example 2:
Input: words = ["omk"]
Output: []
Example 3:
Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]
Constraints:
1 <= words.length <= 20
1 <= words[i].length <= 100
words[i] consists of English letters (both lowercase and uppercase).
思路一:存储字母所在的位置,共分为三类,最后挨个遍历单词,查看单词的字符是否都处于都一个位置即可
public String[] findWords(String[] words) {
String first = "qwertyuiop";
String second = "asdfghjkl";
String third = "zxcvbnm";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < first.length(); i++) {
char ch = first.charAt(i);
map.put(ch, 1);
map.put(Character.toUpperCase(ch), 1);
}
for (int i = 0; i < second.length(); i++) {
char ch = second.charAt(i);
map.put(ch, 2);
map.put(Character.toUpperCase(ch), 2);
}
for (int i = 0; i < third.length(); i++) {
char ch = third.charAt(i);
map.put(ch, 3);
map.put(Character.toUpperCase(ch), 3);
}
List<String> result = new ArrayList<>();
out:
for (String word : words) {
int c = map.get(word.charAt(0));
for (int i = 1; i < word.length(); i++) {
if (map.get(word.charAt(i)) != c) continue out;
}
result.add(word);
}
return result.toArray(new String[0]);
}
标签:map,ch,String,int,easy,put,words,leetcode,500
From: https://www.cnblogs.com/iyiluo/p/16845752.html