C++ solution using set


  • 0
    F
    class Solution {
    public:
        vector<string> findWords(vector<string>& words) {
            //create three lines of char in the keyboard
            set<char> s1({'q','w','e','r','t','y','u','i','o','p'});
            set<char> s2({'a','s','d','f','g','h','j','k','l'});
            set<char> s3({'z','x','c','v','b','n','m'});
            vector<string> re;
            for(int i=0;i<words.size();i++){
                //for each word, checking out if it is validate
                bool f1=false,f2=false,f3=false,flag=false;
                for(int j=0;j<words[i].size();j++){
                    if(s1.find(words[i][j])!=s1.end()){
                        f1=true;
                        if(f2||f3){
                            flag=true;
                            break;
                        }
                    }else if(s2.find(words[i][j])!=s2.end()){
                        f2=true;
                        if(f1||f3){
                            flag=true;
                            break;
                        }
                    }else if(s3.find(words[i][j])!=s3.end()){
                        f3=true;
                        if(f1||f2){
                            flag=true;
                            break;
                        }
                    }
                }
                if(!flag) re.push_back(words[i]);
            }
            return re;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.