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.
Subscribe to see which companies asked this question.
判断一个单词的字母是否都在键盘的同一行。
代码:
class Solution
{
public:
vector<string> findWords(vector<string>& words)
{
s = "QWERTYUIOP";
make_map(1);
s = "ASDFGHJKL";
make_map(2);
s = "ZXCVBNM";
make_map(3);
vector<string>res;
for(auto word:words)
{
int n = 0;
for(auto c:word)
{
int k = toupper(c) - 'A';
if(n != 0 && n != map[k])
{
n = 4;
break;
}
n = map[k];
}
if(n < 4) res.push_back(word);
}
return res;
}
private:
int map[26];
string s;
void make_map(int n)
{
for(auto c:s)
{
map[c-'A'] = n;
}
}
};