Description
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
My solution
基本思路为将单词的字母"分类", 如果跟前面的分类不一致了, 说明跨行了.
class Solution {
public:
vector<string> findWords(vector<string> &words) {
vector<string> res;
string top = "qwertyuiopQWERTYUIOP";
string mid = "asdfghjklASDFGHJKL";
string bot = "zxcvbnmZXCVBNM";
unordered_map<char, int> mp;
for (auto s:top) mp[s] = 1;
for (auto s:mid) mp[s] = 2;
for (auto s:bot) mp[s] = 3;
for (auto word:words) {
bool flag = true;
for (auto w:word) {
if (mp[w] != mp[word[0]]) {
flag = false;
break;
}
}
if (flag) res.push_back(word);
}
return res;
}
};
Discuss
发现一种比较简洁的方式(当然, 利用了find_first_of
内置函数):
class Solution {
public:
vector<string> findWords(vector<string>& words)
{
vector<string> res;
for(auto str : words)
{
bool r1 = str.find_first_of("QWERTYUIOPqwertyuiop") == string::npos ? false : true;
bool r2 = str.find_first_of("ASDFGHJKLasdfghjkl") == string::npos ? false : true;
bool r3 = str.find_first_of("ZXCVBNMzxcvbnm") == string::npos ? false : true;
if(r1 + r2 + r3 == 1)
res.push_back(str);
}
return res;
}
};
Reference
Example
// string::find_first_of
#include <iostream> // std::cout
#include <string> // std::string
#include <cstddef> // std::size_t
int main ()
{
std::string str ("Please, replace the vowels in this sentence by asterisks.");
std::size_t found = str.find_first_of("aeiou");
while (found!=std::string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}
std::cout << str << '\n';
return 0;
}
Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。