500. 键盘行

image-20211031150045980

解题思路:

​ 这题主要就是用哈希表记录下对应字符的行数,而后遍历所有的words判断字符串是否在同一行即可,时间复杂度为O(n*m)(n为words长度,m为单个word长度)

以下为C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
private:
int ch2line[26]={
2,3,3,2,1,2,2,2,1,2,2,2,3,3,1,1,1,1,2,1,1,3,1,3,1,3
};
public:
vector<string> findWords(vector<string>& words) {
int length=words.size();
vector<string> res;
for(int i=0;i<length;i++){
string word=words[i];
int len=word.size();
int type=ch2line[tolower(word[0])-'a'];
int j;
for(j=1;j<len;j++){
if(type!=ch2line[tolower(word[j])-'a']){
break;
}
}
if(j==len) res.push_back(word);
}
return res;
}
};