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.
分析:vector<string>&word 给出N个字符串 将键盘上的每一行字符存储到对应的vector中, 然后循环 word中的每一个string
class Solution {
public:
vector<string> findWords(vector<string>& words) {
unordered_set<char> set1 = {'Q','q','W','w','E','e','R','r','T','t','Y','y','U','u','I','i','O','o','P','p'};
unordered_set<char> set2 = {'S','s','D','d','F','f','G','g','H','h','J','j','K','k','L','l','a','A'};
unordered_set<char> set3 = {'Z','z','X','x','C','c','V','v','B','b','N','n','M','m'};
vector<unordered_set<char>> sets = {set1, set2, set3};
vector<string> out;
for(int i =0;i<words.size();i++){
int index =0;
if(set1.find(words[i][0]) !=set1.end()) index =0;
else if(set2.find(words[i][0]) !=set2.end()) index =1;
else if(set3.find(words[i][0]) !=set3.end()) index =2;
unordered_set<char> tmp =sets[index];
int flag= 0;
for(char c:words[i]){
if(tmp.find(c) !=tmp.end()) continue;
else {
flag =1;
break;
}
}
if(!flag) out.push_back(words[i]);
}
return out;
}
};