leetcode 500

500. KeyboardRow

Problem Description

Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.

Example 1:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.

给出一组字符串,找出满足所有字母在键盘上同一行条件的字符串

METHOD

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<int> keydict(123, 0);
        vector<string> rows({"qwertyuiopQWERTYUIOP", "asdfghjklASDFGHJKL", "zxcvbnmZXCVBNM"});
        for (int i = 0; i < rows.size(); ++i)
            for (char ch : rows[i])
                keydict[ch] = i;
        vector<string> rst;
        for (string word : words)
        {
            int i = keydict[word[0]];
            bool flag = true;
            for (char ch : word)
                if (keydict[ch] != i)
                {
                    flag = false;
                    break;
                }
            if (flag)
                rst.push_back(word);
        }
        return rst;
    }
};