第六道、#500. 键盘行
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
示例:
输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]
注意:
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/keyboard-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
哈希表法:将每行字母设置相同的标记值,然后遍历每个单词的标记值
判断是否都在同一行
class Solution {
public:
vector<string> findWords(vector<string>& words) {
unordered_map<char , int> map;
string s1 = "qwertyuiop"; //第一行字母
string s2 = "asdfghjkl"; //第二行字母
string s3 = "zxcvbnm"; //第三行字母
for(auto c: s1){ //将每行的字母存入哈希表中并赋予标记值
map[c] = 0;
map[c - 32] = 0; //还有大写字母
}
for(auto c: s2){
map[c] = 1;
map[c - 32] = 1;
}
for(auto c: s3){
map[c] = 2;
map[c - 32] = 2;
}
vector<string> ans;
for(auto &word : words){ //遍历字符串数组
int nums = 0;
for(auto c : word){
nums += map[c]; //将每个单词的每个字母的标记值相加
}
if(nums == map[word[0]]*word.size()) ans.push_back(word); //如果都想等则输出到ans
}
return ans;
}
};