3ms c++ unordered_map solution


  • 0
    T
    class Solution {
    public:
        vector<vector<string>> groupStrings(vector<string>& strings) {
            vector<vector<string>> rst;
            unordered_map<string, vector<string>> dict; // <char difference, string>
            for (string &s:strings) {
                string diff = s.size() <= 1 ? "." : string((int)s.size()-1, '0'); // if s.size() == 1
                for (int i = 1, sz = s.size(); i < sz; ++i) {
                    int d = s[i] - s[i-1] + (s[i] < s[i-1] ? 26 : 0); // looping a-z
                    diff[i-1] = d+'0';
                }
               dict[diff].push_back(s);
            }
            for (auto item:dict) {
                rst.push_back(item.second);
            }
            return rst;
        }
    };
    

Log in to reply
 

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