[leetcode-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.

思路:

首先判断第一个字符是属于键盘上的哪一排,然后判断接下来的每一个字符是否都在这一排里出现。

 bool can(string str, vector<unordered_set<char>>& rows)
     {         
         int row = 0;
         for (int k = 0; k<3; ++k)
         {
             if (rows[k].count((char)tolower(str[0])) > 0) row = k;
         }
         for (int i = 1;i<str.size();i++)
         {    
             if (rows[row].count((char)tolower(str[i])) == 0) return false;
         }
         return true;
     }
     vector<string> findWords(vector<string>& words)
     {
         vector<string> ret;
         unordered_set<char> row1{ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
         unordered_set<char> row2{ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' };
         unordered_set<char> row3{ 'z', 'x', 'c', 'v', 'b', 'n', 'm' };

         vector<unordered_set<char>> rows{ row1, row2, row3 };
         for(int i = 0; i < words.size();i++)
         {
             if (can(words[i], rows))
             {
                 ret.push_back(words[i]);
             }
         }
         return ret;
     }

参考:

https://discuss.leetcode.com/topic/77761/c-solution

原文地址:https://www.cnblogs.com/hellowooorld/p/6796524.html