49. Group Anagrams

Problem:

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Solutions:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> anagrams;

        for (auto& str : strs) {
            string anagram = str;
            sort(anagram.begin(), anagram.end());
            anagrams[anagram].push_back(str);
        }

        vector<vector<string>> ret;
        for (auto it = anagrams.begin(); it != anagrams.end(); ++it) {
            ret.push_back(it->second);
        }

        return ret;
    }
};

results matching ""

    No results matching ""