problem:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Hash Table Stringthinking:
(1)很直接想到用hash table来解决这类问题
(2)也可以借用STL map,更加便捷,主键key 存放排序好的string,value 存放指向该string的指针
map<string, vector<const string *> > mapAnagram;
code:
class Solution { public: vector<string> anagrams(vector<string> &strs) { vector<string> ret; map<string, vector<const string *> > mapAnagram; for (vector<string>::const_iterator it = strs.begin(); it != strs.end(); ++it) { string key(*it); sort(key.begin(), key.end()); mapAnagram[key].push_back(&*it); } for (map<string, vector<const string *> >::const_iterator it = mapAnagram.begin(); it != mapAnagram.end(); ++it) { if (it->second.size() > 1) { for (vector<const string *>::const_iterator itstr = it->second.begin(); itstr != it->second.end(); ++itstr) { ret.push_back(**itstr); } } } return ret; } };
原文地址:http://blog.csdn.net/hustyangju/article/details/44753583