原题链接:Leetcode 49. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""] Output: [[""]]
Example 3:
Input: strs = ["a"] Output: [["a"]]
Constraints:
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters.
方法一:排序 思路:
字母异位词值的顺序不同,但是进过排序后得到的字符串是相同的
那么就可以用排序后的字符串作为key,字母异位词链表作为value,维护一个哈希表
最后将哈希表中的内容取出来放到数组中返回即可
class Solution {
public:
vector> groupAnagrams(vector& strs) {
// <排序后的单词, 字母异位词链表>(有点像拉链法)
unordered_map> mp;
// 字母异位词排序之后是相同的
for (auto str: strs) {
string key = str;
sort(key.begin(), key.end());
mp[key].emplace_back(str);
}
vector> ans;
// 每一个value都是一个包含同源异位词的数组
for (auto it = mp.begin(); it != mp.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};
复杂度分析:
- 时间复杂度:O(nklogk),遍历需要n,然后遍历每个单词的过程需要klogk的排序时间,k为单词最大长度
- 空间复杂度:O(nk),n为单词数目,k为单词最大长度,哈希表不会超过nk这个范围



