题目:
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).
思路:
题目比较简单,思路就是用unordered_map记录各个字母属于第几行,然后对于每个单词判断单词内字母是否属于同一行即可。这里unordered_map可以再简化,因为26个字母可以一一对应,所以unordered_map简化为一个26位的字符串,内容是每个字母所在行数,"12210111011122000010020202"是可以的,也算是一个小巧思。
代码:
class Solution {
public:
Solution() {
string s1 = "qwertyuiop";
string s2 = "asdfghjkl";
string s3 = "zxcvbnm";
for (auto &s : s1)
keyboard[s] = 1;
for (auto &s : s2)
keyboard[s] = 2;
for (auto &s : s3)
keyboard[s] = 3;
}
vector<string> findWords(vector<string>& words) {
vector<string> res;
for (auto &w: words) {
int check = -1, yes = 1;
for (auto &c : w) {
char t = c;
if (t >= 'A' && t <= 'Z')
t += 32;
if (check == -1) {
check = keyboard[t];
}
else {
if (check != keyboard[t])
{
yes = 0;
break;
}
}
}
if (yes == 1)
res. push_back(w);
}
return res;
}
private:
unordered_map<char, int> keyboard;
};