Self-evident C++ solution [3 ms]

  • 0

    The idea is simple: for every word check if all the letters belong to the same row.

    set<char> row1 = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
    set<char> row2 = {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
    set<char> row3 = {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
    class Solution {
        vector<string> findWords(vector<string>& words) {
            vector<string> result;
            for(const auto &s : words)
                if(isOneRow(s)) result.push_back(s);
            return result;
        bool isOneRow(const string &s) {
            if (s == "") return true;
            int first = rowNum(s[0]);
            for(int i=1; i<s.size(); i++)
                if(rowNum(s[i]) != first) return false;
            return true;
        int rowNum(char c){
            c = tolower(c);
            if (row1.count(c) != 0) return 1;
            if (row2.count(c) != 0) return 2;
            if (row3.count(c) != 0) return 3;

Log in to reply

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