leetcode 500. 键盘行(Keyboard Row)

题目描述:

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

示例:

输入: 
    ["Hello", "Alaska", "Dad", "Peace"]
输出: 
    ["Alaska", "Dad"]

注意:

  1. 你可以重复使用键盘上同一字符。
  2. 你可以假设输入的字符串将只包含字母。

解法:

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        string s1 = "qwertyuiopQWERTYUIOP";
        string s2 = "asdfghjklASDFGHJKL";
        // string s3 = "zxcvbnmZXCVBNM";
        vector<int> mp(128, 0);
        for(char ch : s1){
            mp[ch] = 1;
        }
        for(char ch : s2){
            mp[ch] = 2;
        }
        vector<string> res;
        for(string word : words){
            int sz = word.size();
            bool canPrint = true;
            for(int i = 1; i < sz; i++){
                if(mp[word[i]] != mp[word[i-1]]){
                    canPrint = false;
                    break;
                }
            }
            if(canPrint){
                res.push_back(word);
            }
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10594235.html