49. Group Anagrams

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.

用STL的sort來把每個字排序。

// Hashtable + STL sort
vector<vector<string>> groupAnagrams(vector<string>& strs) { // time: O(n*str_len*log(str_len)); space: O(n)
    unordered_map<string, vector<string> > m;
    for (string& str : strs) {
        string word = str;
        sort(word.begin(), word.end());
        m[word].push_back(str);
    }
    vector<vector<string> > res;
    for (auto it = m.begin(); it != m.end(); ++it) {
        res.push_back(it->second);
    }
    return res;
}

也可以自己寫一個簡易的sort來排序string,time complexity比較好。

Last updated

Was this helpful?