你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
示例 1:
输入:words = [“Hello”,“Alaska”,“Dad”,“Peace”]
输出:[“Alaska”,“Dad”]
思路:
首先我们建立三个哈希集把对应三行的字母放入。接下来遍历字符串数组,对每个单词进行遍历,统计单词中每个字母出现在哪个哈希集中。然后置为1,如果三个标志相加大于1说明该单词肯定不是同一行里面。如果加起来是1,就是题中要找的单词放进res中。
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> res;
unordered_set<char> row1{'q','w','e','r','t','y','u','i','o','p'};
unordered_set<char> row2{'a','s','d','f','g','h','j','k','l'};
unordered_set<char> row3{'z','x','c','v','b','n','m'};
for(auto s:words){
int one=0,two=0,three=0;
for(auto c:s){
if(c<'a') c+=32; //判断字母的大小写,把大写变为小写
if(row1.count(c)) one=1;
if(row2.count(c)) two=1;
if(row3.count(c)) three=1;
if(one+two+three>1) break;
}
if(one+two+three==1)
res.push_back(s);
}
return res;
}
};