500. Keyboard Row
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.
判断一个字符串的所有字母是否在键盘的同一行
C++(3ms):
1 class Solution { 2 public: 3 vector<string> findWords(vector<string>& words) { 4 unordered_set<char> row1 {'q','w','e','r','t','y','u','i','o','p'} ; 5 unordered_set<char> row2 {'a','s','d','f','g','h','j','k','l'} ; 6 unordered_set<char> row3 {'z','x','c','v','b','n','m'} ; 7 vector<unordered_set<char>> row {row1,row2,row3} ; 8 vector<string> res ; 9 for(string word : words){ 10 int r = -1 ; 11 for(int i = 0 ; i < 3 ; i++){ 12 if (row[i].count(tolower(word[0]))) 13 r = i ; 14 } 15 if (r == -1) 16 continue ; 17 bool flag = true ; 18 for(int j = 1 ; j < word.size() ; j++){ 19 if (row[r].count(tolower(word[j])) == 0){ 20 flag = false ; 21 break ; 22 } 23 } 24 if (flag) 25 res.push_back(word) ; 26 } 27 return res ; 28 } 29 };
Java(4ms):
1 class Solution { 2 public String[] findWords(String[] words) { 3 String[] strs = {"qwertyuiop","asdfghjkl","zxcvbnm"} ; 4 Map<Character,Integer> map = new HashMap<>() ; 5 List<String> res = new LinkedList<>() ; 6 for (int i = 0 ; i < strs.length ; i++){ 7 for (char c : strs[i].toCharArray()){ 8 map.put(c,i) ; 9 } 10 } 11 for(String word : words){ 12 if (word.equals("")) continue ; 13 int index = map.get(word.toLowerCase().charAt(0)) ; 14 for(char c : word.toLowerCase().toCharArray()){ 15 if (map.get(c) != index){ 16 index = -1 ; 17 break ; 18 } 19 } 20 if (index != -1) 21 res.add(word) ; 22 } 23 return res.toArray(new String[res.size()]) ; 24 } 25 }