C++ Solution using map


  • 0
    M
    class Solution {
    public:
        vector<vector<string>> groupStrings(vector<string>& strings) {
        if(strings.size() == 0){
            return vector<vector<string>>();
        }else{
            map<string, vector<string>> my_map;
            map<string, vector<string>>::iterator my_map_it;
            std::vector<string>::iterator it;
            for(it = strings.begin(); it != strings.end(); ++it){
                int temp = (*it)[0] - 'a';
                string temp_s = (*it);
                for(size_t i = 0; i < (*it).length(); ++i){
                    temp_s[i] = 'a' + ((*it)[i] - 'a' - temp + 26) % 26;
                }
                my_map_it = my_map.find(temp_s);
                if (my_map_it != my_map.end()) {
                    (my_map_it->second).push_back(*it);
                }else{
                    vector<string> vect_temp;
                    vect_temp.push_back(*it);
                    my_map.insert(pair<string, vector<string>>(temp_s, vect_temp));
                }
            }
            
            vector<vector<string>> my_vector;
            for (auto it = my_map.begin(); it != my_map.end(); ++it) {
                my_vector.push_back(it->second);
            }
            return my_vector;
        }
    
        }
    };
    

Log in to reply
 

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