最开始的做法因为超时无法通过最后一个样例,后受到启发map的第二个元素可以放置为vector<string>,通过。第一次代码,时间复杂度过大,不贴出来,也不加深自己的映像了
AC代码:(该方法超过36%的提交)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
if(strs.size()<1)
return ans;
map<string,vector<string>> maptest;
map<string,vector<string>>::iterator iter;
for(string s:strs)
{
string temp = s;
sort(temp.begin(),temp.end());
iter = maptest.find(temp);
if(iter==maptest.end()) //不存在
{
vector<string> store;
store.push_back(s);
maptest.insert(map<string,vector<string>>::value_type(temp,store));
}
else //存在
{
iter->second.push_back(s);
}
}
for(iter=maptest.begin();iter!=maptest.end();++iter)
{
ans.push_back(iter->second);
}
return ans;
}
};