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.
解法:
Anagrams 即颠倒字符顺序生成的单词,abc bca 这样的就是,
所以聚集时可以先对str[i]字符排序,然后以该字符串hash映射,则每个key对应的应该是一个str数组,最后把hash中的字符列表输出即可
string getCode(string s){
sort(s.begin(),s.end());
return s;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string> > results;
int size=strs.size();
if(size==0)
return results;
if(size==1){
results.push_back(strs);
return results;
}
map<string,vector<string> > head;
for(int i=0;i<size;++i){
head[getCode(strs[i])].push_back(strs[i]);
}
map<string,vector<string> >::iterator itor=head.begin(),end=head.end();
for(;itor!=end;++itor){
sort(itor->second.begin(),itor->second.end());
results.push_back(itor->second);
}
return results;
}
下边这段代码是我理解题意错误:刚开始不理解Anagrams的意思,以为是产生首位相接的各个list,
解法思想:
sort数组
对首字母建立map,注意,如果是空串,则特殊处理,在第一遍扫描时直接方法结果中
遍历map,在当前itor里,如果queue不为空,说明由以该字母开头的串,依次查找末尾字母开头的串,依次加入tempresult,直到没有以最后字母开头的串;
当前itor的queue为空 itor++;
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string> > results;
int size=strs.size();
if(size==0)
return results;
if(size==1){
results.push_back(strs);
return results;
}
sort(strs.begin(),strs.end());
vector<string> temp;
map<char,queue<int> > head;
for(int i=0;i<size;++i){
if(strs[i]=="")
{
temp.push_back(strs[i]);
}
else
head[strs[i][0]].push(i);
}
if(temp.size()>0)
results.push_back(temp);
temp.clear();
map<char,queue<int> >::iterator itor=head.begin(),end=head.end();
for(;itor!=end;){
if(itor->second.empty()){
++itor;
continue;
}
int i=itor->second.front();
itor->second.pop();
temp.push_back(strs[i]);
char ch=strs[i][0];
char chtail=strs[i].back();
while(head[chtail].empty()==false){
int pos=head[chtail].front();
head[chtail].pop();
temp.push_back(strs[pos]);
}
results.push_back(temp);
temp.clear();
}
return results;
}
原文地址:http://searchcoding.blog.51cto.com/1335412/1695007