Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
思路:这道题要将相同元素的字符串放在相同的数组里,即可采用map按照排序后的字符串作为键,存储字符串(键相同,即可放在同一组)。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>>result;
unordered_map<string,vector<string>> m;
string t;
for(string i : strs)
{
t=i;
sort(t.begin(),t.end());
m[t].push_back(i); //按照排序的键值写入map
}
for(auto i :m)
{
result.push_back(i.second);//将相同键的值写入返回数组
}
return result;
}
};