题目
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.
American keyboard
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) {
}
};
就不翻译了
http://blog.chinaunix.net/uid-26000296-id-3785610.html
http://blog.chinaunix.net/uid-26000296-id-3785623.html
先看看这个做题会有很大帮助
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> result;
vector<set<char>> v(3);
string s1 = "QWERTYUIOPqwertyuiop", s2 = "ASDFGHJKLasdfghjkl", s3 = "ZXCVBNMzxcvbnm";
for (int i = 0; i < s1.length(); i++) v[0].insert(s1[i]);
for (int i = 0; i < s2.length(); i++) v[1].insert(s2[i]);
for (int i = 0; i < s3.length(); i++) v[2].insert(s3[i]);
for (int i = 0; i < words.size(); i++) {
int tag = -1;
bool flag = true;
if (words[i].length() == 0) continue;
if (v[0].find(words[i][0]) != v[0].end()) tag = 0;
if (v[1].find(words[i][0]) != v[1].end()) tag = 1;
if (v[2].find(words[i][0]) != v[2].end()) tag = 2;
for (int j = 1; j < words[i].length(); j++) {
if (v[tag].find(words[i][j]) == v[tag].end()) {
flag = false;
break;
}
}
if (flag == true)
result.push_back(words[i]);
}
return result;
}
};