原题链接: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:
字母异位词值的顺序不同,但是进过排序后得到的字符串是相同的
那么就可以用排序后的字符串作为key,字母异位词链表作为value,维护一个哈希表
最后将哈希表中的内容取出来放到数组中返回即可
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// <排序后的单词, 字母异位词链表>(有点像拉链法)
unordered_map<string, vector<string>> mp;
// 字母异位词排序之后是相同的
for (auto str: strs) {
string key = str;
sort(key.begin(), key.end());
mp[key].emplace_back(str);
}
vector<vector<string>> ans;
// 每一个value都是一个包含同源异位词的数组
for (auto it = mp.begin(); it != mp.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};