Leetcode problem 500, “Keyboard Row”, asks you to determine if a given word can be typed using letters from only one row of a keyboard. The common QWERTY keyboard layout has the following rows:
You are given a list of words, and you need to return the words that can be typed using letters from only one row of this keyboard.
Here’s the C++ implementation:
#include <vector>
#include <string>
#include <unordered_set>
#include <cctype>
using namespace std;
class Solution {
public:
vector<string> findWords(vector<string>& words) {
unordered_set<char> row1 = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
unordered_set<char> row2 = {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
unordered_set<char> row3 = {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
vector<string> result;
for (const string& word : words) {
if (isValid(word, row1) || isValid(word, row2) || isValid(word, row3)) {
result.push_back(word);
}
}
return result;
}
private:
bool isValid(const string& word, const unordered_set<char>& row) {
for (char c : word) {
if (row.find(tolower(c)) == row.end()) {
return false;
}
}
return true;
}
};
Given n words and assuming the average length of a word is m:
This is efficient given the constraints of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?