C++ find unique feature for each group


  • 0
    B

    Since the question asked about the group shifting, so we need to find the group signature, which is the relative distance between consecutive letters in the word. And we can convert the number to string and store them in a HashMap for indexing.

    class Solution {
    public:
        vector<vector<string>> groupStrings(vector<string>& strings) {
            vector<vector<string>>ans;
            unordered_map<string, int>idx;
            for(auto e : strings)
            {
                string s = getIndex(e);
                if(idx.find(s) == idx.end())
                {
                    idx[s] = ans.size();
                    ans.push_back(vector<string>());
                }
                ans[idx[s]].push_back(e);
            }
            return ans;
        }
        
        string getIndex(string s)
        {
            if(s.size() == 1) return "_";
            string ans = "";
            for(int i = 1; i < s.length(); i++)
            {
                int val = s[i] - s[i-1];
                if(val < 0) val += 26;
                ans += "_" + to_string(val);
            }
            return ans;
        }
    };

Log in to reply
 

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