[LeetCode] Group Anagrams

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
string sort(string str) {
std::sort(begin(str), end(str));
return str;
}
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
vector<vector<string>> res;
for(auto& str : strs) {
m[sort(str)].push_back(str);
}
for(auto& entity : m) {
res.push_back(entity.second);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/05/PS/LeetCode/group-anagrams/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.