Saturday, March 7, 2020

500. Keyboard Row -E

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:
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.

A:

-------------------------就是放到set里, 逐个查询。  ---------NOTE: upper() -----------

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        unordered_set<char> S1;
        for(auto ch:"QWERTYUIOP")
            S1.insert(ch);
        unordered_set<char> S2;
        for(auto ch:"ASDFGHJKL")
            S2.insert(ch);
        unordered_set<char> S3;
        for(auto ch:"ZXCVBNM")
            S3.insert(ch);
        vector<string> res;
        for(auto& s : words)
        {
            if(helper(s, S1) || helper(s, S2) || helper(s, S3))
                res.push_back(s);
        }
        return res;
    }
private:
    bool helper(string s, unordered_set<char> &S){
     for(auto c : s)
     {
         if(S.find(toupper(c)) == S.end())
             return false;
     }
        return true;
    }
};







No comments:

Post a Comment