500. Keyboard Row

Problem:

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.

思路

Solution (C++):

vector<string> findWords(vector<string>& words) {
    vector<int> dict(26, 0);
    vector<string> rows{"qwertyuiop", "asdfghjkl", "zxcvbnm"};
    vector<string> res;
    
    for (int i = 0; i < rows.size(); ++i) {
        for (auto c : rows[i]) {
            dict[c-'a'] = 1 << i;
        }
    }
    
    for (auto w : words) {
        int base = 7;
        for (auto c : w) {
            base &= dict[tolower(c)-'a'];
            if (base == 0)  break;
        }
        if (base)  res.push_back(w);
    }
    return res;
}

性能

Runtime: 0 ms  Memory Usage: 6.2 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-04-13 17:03  littledy  阅读(77)  评论(0编辑  收藏  举报