500. Keyboard Row

题目描述:

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.

 

American keyboard

 

Example 1:

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.

解题思路:

判断输入的每个单词中的字母是否都在键盘的同一行上。

代码:

 1 class Solution {
 2 public:
 3     vector<string> findWords(vector<string>& words) {
 4         vector<string> ret;
 5         for (auto word : words) {
 6             bool sig = true;
 7             char c = tolower(word[0]);
 8             int num = alpha[c];
 9             for (int i = 1; i < word.size(); ++i) {
10                 c = tolower(word[i]);
11                 if (alpha[c] != num) {
12                     sig = false;
13                     break;
14                 }
15             }
16             if (sig)
17                 ret.push_back(word);
18         }
19         return ret;
20     }
21     
22     unordered_map<char, int> alpha = {
23         {'q', 1}, {'w', 1}, {'e', 1}, {'r', 1}, {'t', 1}, {'y', 1}, {'u', 1}, {'i', 1}, {'o', 1}, {'p', 1},
24         {'a', 2}, {'s', 2}, {'d', 2}, {'f', 2}, {'g', 2}, {'h', 2}, {'j', 2}, {'k', 2}, {'l', 2},
25         {'z', 3}, {'x', 3}, {'c', 3}, {'v', 3}, {'b', 3}, {'n', 3}, {'m' ,3}
26     };
27 };

 

posted @ 2018-08-13 21:33  gszzsg  阅读(72)  评论(0编辑  收藏  举报