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 lower-case English letters.
Solution
C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string s : strs) {
string tmp = s;
sort(tmp.begin(), tmp.end());
m[tmp].push_back(s);
}
for (auto it : m) {
res.push_back(it.second);
}
return res;
}
};
Explanation

本文介绍了一种高效算法,用于将一组字符串按字谜归类,即把由相同字母组成的字符串分到同一组。通过排序字符串并使用哈希表进行分组,该算法实现了快速匹配和归类,适用于大量英文单词的处理。
472

被折叠的 条评论
为什么被折叠?



