Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
解法分析:
编程珠玑上有介绍,先给每一个string置一个标识,这个标识用来后边的分类,因此用的是降序排列后的strig作为自身的标识。
再将具有相同标识的放在以前。
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string,vector<int>> m1;
vector<vector<string>> result;
for(int i=0;i<strs.size();++i)
{
string s1=strs[i];
sort(s1.begin(),s1.end());
m1[s1].push_back(i);
}
for(auto p:m1)
{
vector<string> v1;
for(auto index:p.second)
v1.push_back(strs[index]);
sort(v1.begin(),v1.end());
result.push_back(v1);
}
return result;
}
};