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"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
思路:就是判断是不是在一行内
代码1:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
if(words.size()==0){return words;}
string a[3]={"qwertyuiop","asdfghjkl","zxcvbnm"};
map<char,int> keyboard;
int i=0;
for(string st:a){
for(char ch:st){
keyboard[ch]=i;
}
i++;
}
vector<string> result;
for(string ss:words){
bool flag=true;
char head=ss[0];
if(head<'a'){head=ss[0]+32;}
for(char ch:ss){
if(ch<'a'){ch=ch+32;}
if(keyboard[head]!=keyboard[ch]){
flag=false;
break;
}
}
if(flag){result.push_back(ss);}
}
return result;
}
};
代码2:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> keyb,res;
map<char,int> m;
keyb.push_back("qwertyuio");
keyb.push_back("asdfghjkl");
keyb.push_back("zxcvbnm");
for(int i=0;i<3;i++){
for(char ch:keyb[i]){m[ch]=i;}
}
for(string word:words){
set<int> temp;
for(char ch:word){
if(isupper(ch)){ch=tolower(ch);}
temp.insert(m[ch]);
}
if(temp.size()==1){res.push_back(word);}
}
return res;
}
};
isupper/islower/toupper/tolower->头文件<cctype>