[leetcode]500. Keyboard Row

Given a List of words, return the words that can be typed using letters of alphabeton only one row's of American keyboard like the image below.

Example:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

分析:

给定一个单词列表,返回其中可以用上图键盘同一行字母组成的单词,字母可以重复。可以将键盘的三行小写字符分别存入三个set中,依次遍历单词中的单词,如果是大写就转换成小写,如果在对应的行出现,相应的标识置1,若最后三行的标识只有一个为1,就将该单词存入结果数组中。

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string>res;
        unordered_set<char>row1{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
        unordered_set<char>row2{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
        unordered_set<char>row3{'z', 'x', 'c', 'v', 'b', 'n', 'm'};
        for(string word : words)
        {
            int one = 0;
            int two = 0;
            int three = 0;
            for(char c : word)
        {            
            if(c < 'a')
                c += 32;
            if(row1.count(c))
                one = 1;
            if(row2.count(c))
                two = 1;
            if(row3.count(c))
                three = 1;                          
        }
            if(one+two+three == 1)
                res.push_back(word);  
        }       
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/86620997