LeetCode 键盘行

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> res;  //定义一个string类型的vector
        unordered_set<char> a{'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};
        unordered_set<char> b{'A','S','D','F','G','H','J','K','L','a','s','d','f','g','h','j','k','l'};
        unordered_set<char>
            c{'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};
        //a,b,c为无序集合,分别包含键盘每行的字母大小写;
        
        for(int i=0;i!=words.size();i++){  //对words中的每一个字符串进行循环
            int x=0;
            int y=0;
            int z=0;//每次处理完一个字符串均要初始化xyz的值,防止后面的判断出错;
            for(int j=0;j!=words[i].size();j++) //对每个字符串中的字符进行循环
            {
              if(a.count(words[i][j])) x=1;
              else if(b.count(words[i][j])) y=1;
              else if(c.count(words[i][j])) z=1; //unordered.count(i)是返回i出现的次数,   若                                                                                    出现某一行键盘的字母,则设置x/y/z=1;
                if(x+y+z>1) break;            //若是出现超过一行的字母,则跳出,进行下一个字                                                                       符串的判断;
            }
            if(x+y+z==1){res.push_back(words[i]);} //若该字符串仅含一行键盘的字母,则将其添                                                                              加至res中;
        }
        return res;
        
    }
};

 

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