原文地址:http://blog.csdn.net/kangrydotnet/article/details/47777545
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.
我 :
1、对map的理解还是不够深刻,是不是应该花时间学习一下?
2、sort 的使用。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string> > result;
sort(strs.begin(),strs.end());
map<string,vector<string>> codeToStrs;
for(int i=0;i<strs.size();i++)
{
codeToStrs[getCode(strs[i])].push_back(strs[i]);
}
for(map<string,vector<string>>::iterator it=codeToStrs.begin();it!=codeToStrs.end();it++)
result.push_back(it->second);
return result;
}
string getCode(string s)
{
sort(s.begin(),s.end());
return s;
}
};