Categories:

Tags:



Problem

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

  • the first row consists of the characters "qwertyuiop",
  • the second row consists of the characters "asdfghjkl", and
  • the third row consists of the characters "zxcvbnm".

Constraints

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] consists of English letters (both lowercase and uppercase).

Solution

The problem Keyboard Row can be solved using a hash map of letters and their rows on a keyboard.

Implementation

class Solution
{
  public:
    vector<string> findWords(vector<string> &words)
    {
        unordered_map<char, char> hashmap;
        string keyboard[3] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        for (int i = 0; i < 3; i++)
            for (char ch : keyboard[i])
                hashmap[ch] = i;

        vector<string> ret;
        for (string str : words)
        {
            bool check = true;
            for (int i = 1; i < str.length(); i++)
                if (hashmap[tolower(str[i])] != hashmap[tolower(str[0])])
                {
                    check = false;
                    break;
                }

            if (check)
                ret.push_back(str);
        }

        return ret;
    }
};