LeetCode 键盘行(hash表)

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

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

注意:

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

思路分析: 使用hash表将各个字符与其出现的行数关联,然后判断字符串的所有字符是否都在同一行。

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        unordered_map<char, int> chRowMap;//chRowMap[ch]用于记录各个字符所在的行数
        vector<string> strs = {"QWERTYUIOPqwertyuiop", "ASDFGHJKLasdfghjkl", "ZXCVBNMzxcvbnm"}, result;
         //关联各个字符所在的行数
        for (int row = 0; row < 3; ++row){
            for (auto ch : strs[row]){
                chRowMap[ch] = row;
            }
        }
        //扫描所有字符串
        for (auto &word : words){
            if (word.size() < 2){
                result.push_back(word);
                continue;
            }
            //判断该字符串是不是所有字母都在同一行
            int row = chRowMap[word[0]], index = 1, wordSize = word.size();
            while (index < wordSize){
                if (chRowMap[word[index]] != row){
                    break;
                }
                index += 1;
            }
            //index移动到尾部说明是同一行
            if (index == wordSize){
                result.push_back(word);
            }
        }
        return result;
    }
};

LeetCode 键盘行(hash表)