500. 键盘行
2024.9.12
题目
给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
- 第一行由字符
"qwertyuiop"组成。 - 第二行由字符
"asdfghjkl"组成。 - 第三行由字符
"zxcvbnm"组成。

提示:
1 <= words.length <= 201 <= words[i].length <= 100words[i]由英文字母(小写和大写字母)组成
示例
示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"]
输出:["Alaska","Dad"]
示例 2:
输入:words = ["omk"]
输出:[]
示例 3:
输入:words = ["adsdf","sfd"]
输出:["adsdf","sfd"]
题解1-哈希表
此时我们已经轻车熟路了,哈希表的键就是26(或者52)个字母,值就是对应的行号。
class Solution {
public:
unordered_map<char,int> hashmap;//值代表行号
void update(string & s,int p){//初始化哈希表
for(char t : s){
hashmap[t] = p - 1;
}
}
bool sameline(string word){
int line = -1;
for (char t : word) {
if (hashmap.find(t) != hashmap.end()) {
if (line == -1) {
line = hashmap[t];
} else if (hashmap[t] != line) {
return false;
}
}
}
return line != -1;
}
vector<string> findWords(vector<string>& words) {
vector<string> samelinewords;
string s1 = "qwertyuiopQWERTYUIOP";
string s2 = "asdfghjklASDFGHJKL";
string s3 = "zxcvbnmZXCVBNM";
update(s1,1),update(s2,2),update(s3,3);
for(const auto& s:words){
if(sameline(s)){
samelinewords.push_back(s);
}
}
return samelinewords;
}
};

1730

被折叠的 条评论
为什么被折叠?



