题目大意:给出一些字符串,判断哪些字符串中的字符是由键盘上同一行字母组成的
分析:集合的应用。判断单词中的所有字母是否在多行出现过,如果多个flag都是true那就不符合要求
代码:
class Solution:
def findWords(self, words: List[str]) -> List[str]:
return list(filter(lambda word: any(set(word.lower()).issubset(line) for line in [set('asdfghjkl'),set('qwertyuiop'),set('zxcvbnm')]),words))
自己的代码:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
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'};
vector<string> ans;
for(auto word : words){
int exist1 = 0,exist2 = 0,exist3 = 0; //单词中的字母是否在123行出现过
for(auto letter : word){
if(!exist1){
if(row1.count(tolower(letter)))
exist1 = 1;
}
if(!exist2){
if(row2.count(tolower(letter)))
exist2 = 1;
}
if(!exist3){
if(row3.count(tolower(letter)))
exist3 = 1;
}
} //只有在一个exist为true的情况下才满足条件,加入答案
if(exist1 + exist2 + exist3 == 1)
ans.push_back(word);
}
return ans;
}
};