Short C++ solution


  • 1
    L
    class Solution {
    public:
        vector<vector<string>> groupStrings(vector<string>& strings) {
            unordered_map<string, vector<string>> dict;
            sort(strings.begin(), strings.end());
            vector<vector<string>> res;
            for (string &s: strings)
                dict[getKey(s)].push_back(s);
            for (auto &kv: dict)
                res.push_back(kv.second);
            return res;
        }
        
        string getKey(string s) {
            int diff = s[0] - 'a';
            for (char &c: s)
                c = (c - diff + 26) % 26 + 'a';
            return s;
        }
    };
    

    key is the shifted string with a starting 'a';


Log in to reply
 

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