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.


img

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.

Code

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        short table[256] = {0};
        vector<string> set{"QWERTYUIOPqwertyuiop","ASDFGHJKLasdfghjkl","ZXCVBNMzxcvbnm"};
        for (int i = 0; i < 3; i++){
            for (char c : set[i]){
                table[c] = i;
            }
        }
        vector<string> result;

        for (int i = 0; i < words.size(); i++){
            short tmpRow = table[words[i][0]];
            bool flag = true;
            for (char c : words[i]){
                if (table[c] != tmpRow){
                    flag = false;
                    break;
                }
            }
            if (flag) result.push_back(words[i]);
        }
        return result;
    }
};

Appendix

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章