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.
想法如下
- 將每個 row 做分群。可以用 set 或是 bit mask,這次使用 bit mask
- 分群 : QWERTYUIOP -> 001,ASDFGHJKL -> 010,ZXCVBNM -> 100
- 將每個字串裡面的字元,對 mask = 111 做 AND,如果最後 mask不為 0,就是要的答案
C++(參考解法)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<string> findWords(vector<string>& words) { | |
int table[26]; | |
const string rows[3] = {"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"}; | |
//>> QWERTYUIOP -> 001 | |
//>> ASDFGHJKL -> 010 | |
//>> ZXCVBNM -> 100 | |
for(int i = 0; i < 3; i++) { | |
for(const auto &c : rows[i]) { | |
table[c - 'A'] = 1 << i; | |
} | |
} | |
int mask; | |
vector<string> ans; | |
for(const auto &s : words) { | |
mask = 7; //>> 111 | |
for(const auto &c : s) { | |
mask &= table[toupper(c) - 'A']; | |
if(mask == 0) { | |
break; | |
} | |
} | |
if(mask != 0) { | |
ans.push_back(s); | |
} | |
} | |
return ans; | |
} | |
}; |
Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String[] findWords(String[] words) { | |
int[] table = new int[26]; | |
final String[] rows = new String[]{"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"}; | |
//>> QWERTYUIOP -> 001 | |
//>> ASDFGHJKL -> 010 | |
//>> ZXCVBNM -> 100 | |
for(int i = 0; i < 3; i++) { | |
for(final char c : rows[i].toCharArray()) { | |
table[c - 'A'] = 1 << i; | |
} | |
} | |
int mask; | |
ArrayList<String> ans = new ArrayList<>(); | |
for(final String s : words) { | |
mask = 7; | |
for(final char c : s.toCharArray()) { | |
mask &= table[Character.toUpperCase(c) - 'A']; | |
if(mask == 0) { | |
break; | |
} | |
} | |
if(mask != 0) { | |
ans.add(s); | |
} | |
} | |
return ans.toArray(new String[0]); | |
} | |
} |
沒有留言:
張貼留言