Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
对每个字符串进行排序,然后对排过序的字符串统计出现次数超过1次的。将这些超过1次的字符串的原始串加入结果集
vector<string> anagrams(vector<string> &strs) { //C++ vector<string> result; if(strs.size() == 0) return result; vector<string> vec(strs.begin(),strs.end()); for(int i = 0; i < vec.size(); i++) sort(vec[i].begin(),vec[i].end()); map<string,int> tmap; for(int i = 0; i < vec.size(); i++) tmap[vec[i]] += 1; set<string> tset; for(map<string,int>::iterator iter = tmap.begin(); iter != tmap.end(); iter++) if(iter->second > 1) tset.insert(iter->first); for(int i = 0; i < vec.size(); i++) { if(tset.count(vec[i] )== 1) result.push_back(strs[i]); } return result; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/41552951