Leetcode 500. 键盘行

题目

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容