500.Keyboard Row

500.Keyboard Row

难度:Easy

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

示例:

输入: ["Hello", "Alaska", "Dad", "Peace"] 输出: ["Alaska", "Dad"]

注意: 你可以重复使用键盘上同一字符。 你可以假设输入的字符串将只包含字母。

代码如下:

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> res;
        for(auto w: words)
        {
            int id=getid(w[0]);
          //  cout<<id<<endl;
            int len=w.length();
            int i;
            for(i=1;i<len;i++)
                if(!(l[id].count(w[i]) ||l[id].count(w[i]+32) ) )
                    break;
            if(i==len) res.push_back(w);
        }
        return res;
        
    }
private:
    vector<unordered_set<char>> l={\{'q','w','e','r','t','y','u','i','o','p'},{'a','s','d','f','g','h','j','k','l'},{'z','x','c','v','b','n','m'} };
   // unordered_set<char> l1={'q','w','e','r','t','y','u','i','o','p'};
   // unordered_set<char> l2={'a','s','d','f','g','h','j','k','l'};
  //  unordered_set<char> l3={'z','x','c','v','b','n','m'};
    int getid(char a)
    {
        for(int i=0;i<3;i++)
            if(l[i].count(a) || l[i].count(a+32)) return i;
        //cout<<a<<endl;
       // cout<<l[1].count('h')<<endl;
        return -1;
    }
};

Last updated