Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
Example 1:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
给定一系列单词,需要我们来查看组成单个单词的所有字母是否在键盘的同一行中,如果是的话则将其添加到返回结果中。
可以建立三个字符串,分别就是键盘上的三行字母,然后开始遍历所有的单词,判断这个单词的所有字母是否都存在与某一行中,需要注意的是大小写的转换。
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> ans;
vector<string> rows = {"qwertyuiop","asdfghjkl","zxcvbnm"};
for(string word : words) {
bool row1 = true;// 用来标记在不在这一行中
bool row2 = true;
bool row3 = true;
for(char ch : word) {
if(row1) {
if(rows[0].find(tolower(ch)) == -1)
row1 = false;
}
if(row2) {
if(rows[1].find(tolower(ch)) == -1)
row2 = false;
}
if(row3) {
if(rows[2].find(tolower(ch)) == -1)
row3 = false;
}
}
if(row1 || row2 || row3) {
ans.push_back(word);
}
}
return ans;
}
};
也可以将三行的按键字母存放在hash表中,某一行的字母对应一个数字,比如第一行的字母用1里表示,第二行用2,第三行用3。然后看单词的第一个字母是属于哪一行的,然后对比该单词的其他字母是否与第一行相同。
比如单词:apple,第一个字母在hash表中的对应的字母是2,但是p在hash表中对应的是1,所以不相同,也就能够说明这个单词的所有字母不在同一行中。
class Solution {
public:
vector<string> findWords(vector<string>& words) {
// 用来转换为小写
class uTol{
public:
char easytolow(char in){
if(in <= 'Z' && in >= 'A'){
return in - ('Z' - 'z');
}
return in;
}
};
// 用一个map来标记行数
unordered_map<char, int> style;
for(auto letter:"qwertyuiop"){
style[letter] = 1;
}
for(auto letter:"asdfghjkl"){
style[letter] = 2;
}
for(auto letter:"zxcvbnm"){
style[letter] = 3;
}
uTol ul;
vector<string> result;
for(auto word: words){
// 检查第一个元素是什么类型的
int category = style[ul.easytolow(word[0])];
bool isAllsame = true;
// 检查该单词的所有字母
for(auto letter:word){
// 如果和第一个单词不一个类型
if(style[ul.easytolow(letter)] != category){
isAllsame = false;
break;
}
}
if(isAllsame){
result.push_back(word);
}
}
return result;
}
};