文章目录
一、题目
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 <= strsi.length <= 100
strsi consists of lowercase English letters.
二、题解
cpp
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int n = strs.size();
unordered_map<string,vector<string>> map;
for(int i = 0;i < n;i++){
string s = strs[i];
sort(s.begin(),s.end());
map[s].emplace_back(strs[i]);
}
vector<vector<string>> res;
//遍历所有的key
for(auto it = map.begin();it != map.end();it++){
res.emplace_back(it->second);
}
return res;
}
};