Group Anagrams

LeetCode #49


Description:

Given an array of strings, group anagrams together.

Example:

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Idea:

Use unordered_map<string, vector<string>> hash_map.

Sort each string as key, push each string into the vector. That's it.

Code:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;

        unordered_map<string, vector<string>> hash_map;

        for(auto & e: strs){
            string key = e;
            sort(key.begin(), key.end());
            hash_map[key].push_back(e);
        }

        for(auto & e: hash_map){
            result.push_back(e.second);
        }

        return result;
    }
};

results matching ""

    No results matching ""