leetcode-2-basic

解题思路:

题目本身挺简单的,考虑用set,判断每个单词的字母是不是属于同一个集合。需要注意的是:1)set的构造方法;2)单词可能是大小写混合的,不一定只是首字母大写;

3)break是跳出循环=。=switch写的时候要注意,不好用的话还是用if-else好了。

    vector<string> findWords(vector<string>& words) {
        char f[20] = {'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};
        set<char>first(f,f+20);
        char s[18] = {'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};
        set<char>second(s, s+18);
        char t[14] = {'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};
        set<char>third(t, t+14);
        vector<string>::iterator it;
        string temp = "";
        vector<string> result;
        bool flag = true;
        int i;
        for (it = words.begin(); it != words.end(); it++) {

            temp = *it;
            flag = true;

            if (temp.length() == 1) {
                result.insert(result.end(), temp);
                continue;
            }
           if (first.find(temp[0]) != first.end()) {
                    for (i = 1; i < temp.length(); i++) {
                        if (first.find(temp[i]) == first.end()) {
                            break;
                        }
                    }
                    if (i != temp.length()) {
                        flag = false;
                        continue;
                    }
                    }
            else if (second.find(temp[0]) != second.end()) {
                    for (i = 1; i < temp.length(); i++) {
                        if (second.find(temp[i]) == second.end()) {
                            break;
                        }
                    }
                    if (i != temp.length()) {
                        flag = false;
                        continue;
                    }
                    }
             else {
                    for (i = 1; i < temp.length(); i++) {
                        if (third.find(temp[i]) == third.end()) {
                            break;
                        }
                    }
                    if (i != temp.length()) {
                        flag = false;
                        continue;
                    }
                    }
                
            if (flag == true) {
                result.insert(result.end(), temp);
            }
        }
        return result;
    }

 

原文地址:https://www.cnblogs.com/pxy7896/p/6478599.html