[LeetCode] Keyboard Row 键盘行

旧城等待, 2022-02-01 09:15 353阅读 0赞

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:

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

这道题给了我们一些单词,问哪些单词可以由键盘上的一行中的键符打出来,难度其实并不大。首先我们把键盘的三行字符分别保存到三个set中,然后遍历每个单词中的每个字符,分别看当前字符是否在三个集合中,如果在,对应的标识变量变为1,我们统计三个标识变量之和就知道有几个集合参与其中了,参见代码如下:

  1. class Solution {
  2. public:
  3. vector<string> findWords(vector<string>& words) {
  4. vector<string> res;
  5. unordered_set<char> row1{
  6. 'q','w','e','r','t','y','u','i','o','p'};
  7. unordered_set<char> row2{
  8. 'a','s','d','f','g','h','j','k','l'};
  9. unordered_set<char> row3{
  10. 'z','x','c','v','b','n','m'};
  11. for (string word : words) {
  12. int one = 0, two = 0, three = 0;
  13. for (char c : word) {
  14. if (c < 'a') c += 32;
  15. if (row1.count(c)) one = 1;
  16. if (row2.count(c)) two = 1;
  17. if (row3.count(c)) three = 1;
  18. if (one + two + three > 1) break;
  19. }
  20. if (one + two + three == 1) res.push_back(word);
  21. }
  22. return res;
  23. }
  24. };

本文转自博客园Grandyang的博客,原文链接:Keyboard Row 键盘行,如需转载请自行联系原博主。

发表评论

表情:
评论列表 (有 0 条评论,353人围观)

还没有评论,来说两句吧...

相关阅读

    相关 500. Keyboard Row

    [原题链接][Link 1] 这道题如果是自己做的话,应该就是遍历了。 但是在discuss区有个非常巧妙的做法,这里就贴上来 public class P50