easy c++ hashtable solution


  • 0
    vector<string> findWords(vector<string>& words) 
    {
        vector<string> result;
        string strs[3] = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
        int hash[26] = {0};
        for (int i = 1; i < 3; i++)
        {
            string str = strs[i];
            for (auto c : str)
            {
                hash[tolower(c) - 'a'] = i;
            }
        }
        
        for (auto word : words)
        {
            if (isKbrow(word, hash))
                result.push_back(word);  
        }
        
        return result;
    }
    
    bool isKbrow(const string& word, const int hash[])
    {
        for (int i = 0; i < word.size(); i++)
        {
            if (hash[tolower(word[i]) - 'a'] != hash[tolower(word[0]) - 'a'])
                return false;
        }
        return true;
    }

Log in to reply
 

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