leetcode 500. Keyboard Row


Description
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

My solution
基本的な考え方は単語のアルファベットを「分類」し、前の分類と一致しなければ、行をまたぐことを説明する.
class Solution {
public:
    vector findWords(vector &words) {
        vector res;
        string top = "qwertyuiopQWERTYUIOP";
        string mid = "asdfghjklASDFGHJKL";
        string bot = "zxcvbnmZXCVBNM";
        unordered_map mp;
        for (auto s:top) mp[s] = 1;
        for (auto s:mid) mp[s] = 2;
        for (auto s:bot) mp[s] = 3;
        for (auto word:words) {
            bool flag = true;
            for (auto w:word) {
                if (mp[w] != mp[word[0]]) {
                    flag = false;
                    break;
                }
            }
            if (flag) res.push_back(word);
        }
        return res;
    }
};

Discuss
比較的簡潔な方法が発見された(もちろん、find_first_of内蔵関数が利用されている):
class Solution {
public:

vector findWords(vector& words) 
{
    vector res;
    
    for(auto str : words)
    {
        bool r1 = str.find_first_of("QWERTYUIOPqwertyuiop") == string::npos ? false : true;
        bool r2 = str.find_first_of("ASDFGHJKLasdfghjkl") == string::npos ? false : true;
        bool r3 = str.find_first_of("ZXCVBNMzxcvbnm") == string::npos ? false : true;
        
        if(r1 + r2 + r3 == 1)
            res.push_back(str);
    }
    
    return res;
}
    
};

Reference
  • leetcode 500. Keyboard Row
  • find_first_of

  • Example
    // string::find_first_of
    #include        // std::cout
    #include          // std::string
    #include         // std::size_t
    
    int main ()
    {
      std::string str ("Please, replace the vowels in this sentence by asterisks.");
      std::size_t found = str.find_first_of("aeiou");
      while (found!=std::string::npos)
      {
        str[found]='*';
        found=str.find_first_of("aeiou",found+1);
      }
    
      std::cout << str << '
    '; return 0; }
    Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.