Given an array of strings, group anagrams together.
思路:将字符相同的子串归为一类。由于各字符是乱序的,我们先将个string按照字符顺序的排序,然后使用hash表就可以判断哪些string应该归为一类。用map将一类的string储存起来,最后全部归在同一个vector下就可以了。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>>result;
if(strs.size() == 0) {
return result;
}
map<string, vector<string>>hash;
for (int i = 0; i < strs.size(); i++) {
string temp = strs[i];
sort(temp.begin(), temp.end());
hash[temp].push_back(strs[i]);
}
map<string, vector<string>>::reverse_iterator it = hash.rbegin();
while (it != hash.rend()) {
result.push_back(it -> second);
it++;
}
return result;
}
};