LeetCode 500.键盘行
原题链接 ==10.31==
题目描述:
给你一个字符串数组 words
,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。
美式键盘 中:
- 第一行由字符
"qwertyuiop"
组成。 - 第二行由字符
"asdfghjkl"
组成。 - 第三行由字符
"zxcvbnm"
组成。
代码:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
string line[3] = {
"qwertyuiop",
"asdfghjkl",
"zxcvbnm"
};
vector<string> res;
unordered_map<char, int> hash;
for (int i = 0; i < 3; i ++ ){
for (auto& c : line[i])
hash[c] = i;
}
for (auto word : words){
set<int> S;
for (auto c : word){
S.insert(hash[tolower(c)]);
}
if (S.size() == 1) res.push_back(word);
}
return res;
}
};
- 使用
unordered_map<char, int>
存储每个字母出现在哪一行。- 输入的字符串中存在大写字母,在查找存在哪一行时需要转换成小写,使用
tolower()
函数- 利用
set
的特性存储每个行的字母出现的次数