LeetCode "Group Shifted Strings"

Use constructive strategy: we compose each of the 26 variations of one word.

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) 
    {
        vector<vector<string>> ret;

        unordered_map<string, unsigned> hm;
        for (auto &s : strings) hm[s]++;

        for (auto &s : strings)
        {
            vector<string> cret;
            
            int offset = s[0] - 'a';
            string curr;
            for (auto c : s)
            {
                char nc = c - offset;
                if (nc >= 'a')    curr += nc;
                else            curr += c + 26 - offset;
            }

            for (int i = 0; i < 26; i++)
            {
                //    move on word
                if (i > 0)
                {
                    for (int i = 0; i < curr.length(); i++)
                    {
                        curr[i] += 1;
                        if (curr[i] > 'z') curr[i] = 'a';
                    }
                }
                //
                if (hm.find(curr) != hm.end())
                {
                    for (int i = 0; i < hm[curr]; i ++)        cret.push_back(curr);
                    hm.erase(curr);
                }
            }
            if (!cret.empty())    ret.push_back(cret);
        }

        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4754425.html