题目
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
keyboard.png
示例:
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
C++解法
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
class Solution {
public:
set<set<char>> keyboard = {
{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'},
{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'},
{'z','x', 'c', 'v', 'b', 'n', 'm'}
};
vector<string> findWords(vector<string>& words) {
vector<string> matchedWords;
set<char> item_set;
bool match = false;
for (auto word: words) {
item_set.clear();
for (auto c: word) {
char character = tolower(c);
if (item_set.count(character) == 0) item_set.insert(character);
}
for (auto set: keyboard) {
match = true;
for (auto c: item_set) {
if (set.count(c) == 0) { match = false; break;};
}
if (match) {matchedWords.push_back(word); break; }
}
}
return matchedWords;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
Solution solution;
vector<string> vec = {"Hello","Alaska","Dad","Peace"};
auto result = solution.findWords(vec);
for (auto item: result) cout << item << " "; cout << endl;
return 0;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/keyboard-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。