C++ solution with unordered_map


  • 0
    O

    Use the letters on the keyboards as keys in a dictionary and the row number as values.
    Then check if the previous letter in the word was in the same row as the current letter!

    vector<string> findWords(vector<string>& words) {
            //The dumbest way to initialize it!
            unordered_map<char, int> kbRow({
                {'q', 1}, {'w',1}, {'e', 1}, {'r',1},
                {'t', 1}, {'y',1}, {'u', 1}, {'i',1},
                {'o', 1}, {'p',1}, {'a', 2}, {'s',2},
                {'d', 2}, {'f',2}, {'g', 2}, {'h',2},
                {'j', 2}, {'k',2}, {'l', 2}, {'z',3},
                {'x', 3}, {'c',3}, {'v', 3}, {'b',3},
                {'n', 3}, {'m',3},
            });
            vector<string> sameRowWords;
            bool sameRow;
            char prevL;
            for(string word : words){
                sameRow = true;
                prevL = tolower(word[0]);
                for(char letter : word){
                    letter = tolower(letter);
                    if(kbRow[prevL] != kbRow[letter]){
                        sameRow = false;
                        break;
                    }
                }
                if(sameRow) sameRowWords.push_back(word);
            }
            return sameRowWords;
        }
    

Log in to reply
 

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