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.
Code
class Solution {
public:
vector<string> findWords(vector<string>& words) {
short table[256] = {0};
vector<string> set{"QWERTYUIOPqwertyuiop","ASDFGHJKLasdfghjkl","ZXCVBNMzxcvbnm"};
for (int i = 0; i < 3; i++){
for (char c : set[i]){
table[c] = i;
}
}
vector<string> result;
for (int i = 0; i < words.size(); i++){
short tmpRow = table[words[i][0]];
bool flag = true;
for (char c : words[i]){
if (table[c] != tmpRow){
flag = false;
break;
}
}
if (flag) result.push_back(words[i]);
}
return result;
}
};
Appendix
- Link: https://leetcode.com/problems/keyboard-row/
- Run Time: 0ms