C++ 3ms 11 lines


  • 0

    Grouping the strings using keys starting with 'a' is not the only option. As a matter of fact, I found it a lot cleaner to shift the strings to start with 'z'.

    vector<vector<string>> groupStrings(vector<string>& strings) {
            unordered_map<string, vector<string>> groups;
            
            for (string s : strings) {
                string key = s;
                for (int i = 0, shift = 'z' - s[0]; i < s.length(); i++)
                    key[i] = 'a' + (s[i] - 'a' + shift) % 26;
                
                groups[key].push_back(s);       // group the strings using keys starting with 'z'
            }
            
            vector<vector<string>> ans;
            for (auto it = groups.begin(); it != groups.end(); it++)
                ans.push_back(it->second);      // construct answer
            
            return ans;
    }
    

Log in to reply
 

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