500. Keyboard Row

  • Difficulty: Easy

  • Topics: Hash Table

  • Similar Questions:

Problem:

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:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

 

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Solutions:

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> ret;
        for (auto& word : words) {
            if (sameRow(word)) {
                ret.push_back(word);
            }
        }

        return ret;
    }

private:
    bool sameRow(const string& str) {
        if (str.length() == 0)  return true;
        char c = tolower(str[0]);
        int row = -1;
        for (int i = 0; i < 3; ++i) {
            if (board[i].find(c) != string::npos) {
                row = i;
                break;
            }
        }

        for (int i = 1; i < str.length(); ++i) {
            if (board[row].find(tolower(str[i])) == string::npos)   return false;
        }

        return true;
    }

    vector<string> board = {
        "qwertyuiop",
        "asdfghjkl",
        "zxcvbnm"
    };
};

results matching ""

    No results matching ""