C++ optimized solution


  • 0
    B

    C++ Solution

    class Solution {
    public:
        vector<string> findWords(vector<string>& words) {
            std::vector<std::string> results;
            bool test = true, first = true;
            int row;
            initRows();
            for(std::string word : words) {
                first = true;
                test = true;
                for(char ch : word) {
                    if(first) {
                        first = false;
                        if(rows[0].find(std::tolower(ch)) != rows[0].end()) {
                            row = 0;
                            continue;
                        }
                        
                        if(rows[1].find(std::tolower(ch)) != rows[1].end()) {
                            row = 1;
                            continue;
                        }
                        
                        if(rows[2].find(std::tolower(ch)) != rows[2].end()) {
                            row = 2;
                            continue;
                        }
                        
                        test = false;
                    } else {
                        if(rows[row].find(std::tolower(ch)) == rows[row].end())
                            test = false;
                        if(!test)
                            break;
                    }
                }
                if(test)
                    results.push_back(word);
            }
            return results;
        }
    private:
        std::vector<std::unordered_set<char>> rows;
        
        void initRows() {
            std::unordered_set<char> one {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
            std::unordered_set<char> two {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
            std::unordered_set<char> tri {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
            rows.push_back(one);
            rows.push_back(two);
            rows.push_back(tri);
        }
    };
    

Log in to reply
 

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