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.
sln
- 创建一个数字,记录26个字符分别属于哪一行(一个由0,1,2组成的数组)
- 遍历每个单词,可以用O(1)的时间确定字母属于哪一行,那么可以用O(m)的时间确定整个单词是否可以用键盘的其中一行打出来,其中m为字符串长度
- 用O(n * m)的时间可以完成整个任务,c++实现如下
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> ret;
int belongTo[] = {1, 2, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 2, 0, 2};
for (vector<string>::iterator it = words.begin(); it != words.end(); it++) {
string word = *it;
int group = -1;
bool flag = true;
for (int i = 0; i < word.length(); i++) {
int cgroup = belongTo[toLower(word[i]) - 'a'];
if (group != -1 && group != cgroup) {
flag = false;
break;
} else {
group = cgroup;
}
}
if (flag) {
ret.push_back(word);
}
}
return ret;
}
private:
char toLower(char a) {
if (a >= 'A' && a <= 'Z') {
return 'a' + (a - 'A');
}
return a;
}
};