1. 程式人生 > >500. Keyboard Row

500. Keyboard Row

strong 分享 char ima 描述 note hab using ble

題目描述:

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:

  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 };

500. Keyboard Row