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.
找出字符串数组中那些每个字符串的组成字母都是由键盘中的同一行字母组成的字符串。首先先建立三个查找表,每个表都是由键盘中的每行字母组成。接着循环数组中每个字符串,判断它的每个字母是否都可以在同一查找表中找到。最后将符合条件的字符串放入返回数组中。
class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> res; 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'}; for (string word : words) { int i = 0, j = 0, k = 0; int n = word.size(); for (char c : word) { if (c < 'a') c += 32; if (row1.count(c)) i++; if (row2.count(c)) j++; if (row3.count(c)) k++; } if (i == n || j == n || k == n) res.push_back(word); } return res; } }; // 3 ms