[leetcode] 500. Keyboard Row

题目:

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.


American keyboard


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.

代码:

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> key;
        vector<string> res;
        key.push_back("qwertyuiopQWERTYUIOP");
        key.push_back("asdfghjklASDFGHJKL");
        key.push_back("ZXCVBNMzxcvbnm");
        for(int i = 0; i < words.size(); i++){
            int index;
            for(int j = 0; j < 3; j++){
                if(key[j].find(words[i][0]) != string::npos){
                    index = j;
                    break;
                }
            }
            int flag = 1;
            for(int j = 1; j < words[i].size(); j++){
                if(key[index].find(words[i][j]) == string::npos){
                    flag = 0;
                    break;
                }
            }
            if(flag == 1) res.push_back(words[i]);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/80326730