500. Keyboard Row
Posted gsz-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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.
解题思路:
判断输入的每个单词中的字母是否都在键盘的同一行上。
代码:
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的主要内容,如果未能解决你的问题,请参考以下文章