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 <= 10^4`
• `0 <= strs[i].length <= 100`
• `strs[i]` consists of lowercase English letters.

``````class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, int> m;
for (string str : strs) {
string t = str;
sort(t.begin(), t.end());
if (!m.count(t)) {
m[t] = res.size();
res.push_back({});
}
res[m[t]].push_back(str);
}
return res;
}
};
``````

``````class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
vector<int> cnt(26);
string t;
for (char c : str) ++cnt[c - 'a'];
for (int i = 0; i < 26; ++i) {
if (cnt[i] == 0) continue;
t += string(1, i + 'a') + to_string(cnt[i]);
}
m[t].push_back(str);
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/49

Valid Anagram

Group Shifted Strings

Find Resultant Array After Removing Anagrams

Count Anagrams

https://leetcode.com/problems/group-anagrams/

https://leetcode.com/problems/group-anagrams/discuss/19176/share-my-short-java-solution

https://leetcode.com/problems/group-anagrams/discuss/19200/10-lines-76ms-easy-c-solution-updated-function-signature

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation