500. 键盘行
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
示例1:
输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]
注意:
1、你可以重复使用键盘上同一字符。
2、你可以假设输入的字符串将只包含字母。
思路
刚接触hash,专门练了这一块,unordered_map分别为三行字母建立hash表;下面第一步先判断这个单词第一个字母属于哪一行的,并且统计这个单词中字母属于这一行的数量,如果等于单词长度那就说明符合要求,push进resV。
class Solution {
public:
vector<string> findWords(vector<string>& words) {
std::unordered_map<char,int> first_row({{'Q',1},{'W',1},{'E',1},{'R',1},{'T',1},{'Y',1},{'U',1},{'I',1},{'O',1},{'P',1},{'q',1},{'w',1},{'e',1},{'r',1},{'t',1},{'y',1},{'u',1},{'i',1},{'o',1},{'p',1}});
std::unordered_map<char,int> second_row({{'A',1},{'S',1},{'D',1},{'F',1},{'G',1},{'H',1},{'J',1},{'K',1},{'L',1},{'a',1},{'s',1},{'d',1},{'f',1},{'g',1},{'h',1},{'j',1},{'k',1},{'l',1}});
std::unordered_map<char,int> third_row({{'Z',1},{'X',1},{'C',1},{'V',1},{'B',1},{'N',1},{'M',1},{'z',1},{'x',1},{'c',1},{'v',1},{'b',1},{'n',1},{'m',1}});
vector<string> resV;
int n=words.size();
for(string str:words){
if(first_row.find(str[0])!=first_row.end()){
int cnt_tp=1;
for(int j1=1;j1<str.size();j1++){
if(first_row.find(str[j1])!=first_row.end()){cnt_tp++;}
}
if(cnt_tp==str.size()){resV.push_back(str);}
}
else if(second_row.find(str[0])!=second_row.end()){
int cnt_tp=1;
for(int j1=1;j1<str.size();j1++){
if(second_row.find(str[j1])!=second_row.end()){cnt_tp++;}
}
if(cnt_tp==str.size()){resV.push_back(str);}
}
else
{int cnt_tp=1;
for(int j1=1;j1<str.size();j1++){
if(third_row.find(str[j1])!=third_row.end()){cnt_tp++;}
}
if(cnt_tp==str.size()){resV.push_back(str);}
}
}
return resV;
}
};