In The Same Line

In The Same Line

题目描述:

给定一组字符串,判断每个字符串中的字符是否在键盘上的同一行。

例子:

具体描述看LeetCode500

解题思路:

构建每一行键盘的哈希表,然后对每个字符串中的字符分别进行判断即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> res;
set<char> hash1 = {'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};
set<char> hash2 = {'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};
set<char> hash3 = {'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};
for (int i = 0; i < words.size(); i++){
if (allIn(hash1, words[i]) || allIn(hash2, words[i]) ||allIn(hash3, words[i]))
res.push_back(words[i]);
}
return res;
}
bool allIn(set<char>hash, string str){
for(int i = 0; i < str.size(); i++){
if (hash.find(str[i]) == hash.end())
return false;
}
return true;
}
};