Sharing my C++ solution


  • 1
    T
    class Solution {
    private:
        string newString(string s)
        {
            string result = "0";
            for(int i=1; i<s.length(); i++)
            {
                int diff = s[i]-s[i-1];
                if(diff<0)
                    diff = diff+26;
                char c = diff+'a';
                result = result + c;
            }
            
            return result;
        }
        
    public:
        vector<vector<string>> groupStrings(vector<string>& strings) {
            int n = strings.size(), i;
            unordered_map<string, vector<string>> myMap;
            for(i=0; i<n; i++)
            {
                string s = newString(strings[i]);
                myMap[s].push_back(strings[i]);
            }
            
            vector<vector<string>> result;
            i=0;
            for(auto x=myMap.begin(); x!=myMap.end(); x++)
            {
                result.push_back(x->second);
                sort(result[i].begin(), result[i].end());
                i++;
            }
            
            return result;
        }
    };

Log in to reply
 

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