LeetCode500 Keyboard Row

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

keyboard row

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
2
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

思路

判断一个字符串是不是由键盘上同一行的字符组成的,若是则输出该字符串。

将同一行的字符用map映射到同一个值,然后再对输入的字符串逐个字符比较判断即可。

注意大小写的问题。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<string> findWords(vector<string>& words) {
string r[3] = {"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"};
unordered_map<char, int> hs;
for (int i = 0; i < 3; ++i) for (auto& c: r[i]) hs[c] = i;
vector<string> ans;
for(auto& s: words) {
int row = hs[toupper(s[0])], ok = 1;
for (auto& c: s) if (hs[toupper(c)] != row) ok = 0;
if (ok) ans.push_back(s);
}
return ans;
}
};
分享到 评论