3ms C++ Solution using Hash Table


  • 0
    L

    Basically use a hash table, and you do shifting on each word so that the first letter become 'a', then the resulting string should be a key that allow you to group strings on a hash table.

    """
    class Solution {
    public:

    string shifttoabegin(string input){
        int countshift = 0;
        
        if(input[0] == 'a')
            return input;
        string result = "a";
        
        
        char check = input[0];
        while(check!= 'z'){
            countshift++;
            check = check + 1;
        }
        
        countshift++;
        
        for(int i = 1; i < input.length(); i++){
            check = input[i];
            for(int j = 0;j < countshift; j++){
                if(check!='z'){
                    check = check +1;
                }else{
                    check = 'a';
                }
            }
            result += check;
        }
    
        return result;
    }
    
    vector<vector<string>> groupStrings(vector<string>& strings) {
        vector<vector<string>> result;
        unordered_map<string, vector<string>> pattern_match;
        for(int i = 0; i < strings.size(); i++){
            pattern_match[shifttoabegin(strings[i])].push_back(strings[i]);
        }
        for ( auto it = pattern_match.begin(); it != pattern_match.end(); ++it ){
            result.push_back(it->second);
        }
        return result;
    }
    

    };

    """


Log in to reply
 

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