Description
Given an array of strings, group anagrams together.
Example
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
Note
- All inputs will be in lowercase.
- The order of your output does not matter.
Analyse
题意为将由相同字母组合而成的单词分到一块。我的主要思路是,把单词内部的字母按照字典序排好序,然后形成新的单词作为那一类的代表,然后把具有相同排序的单词归在一起就好。
这题有点特殊,我几乎是只借用STL来完成这道题的,因为用了STL之后,这道题真的变得很简单。假如不用STL的话,需要自己写map,vector等东西,有点麻烦。
Code
class Solution {
public:
vector<vector<string> > groupAnagrams(vector<string>& strs) {
if (strs.empty()) return vector<vector<string> >();
vector<vector<string> > ans;
map<string,vector<string> > ans_map;
for (int i = 0; i < strs.size(); i++) {
char* st = new char[strs[i].length()];
strcpy(st, strs[i].c_str());
sort(st, st + strs[i].length());
string keyst = st;
if (ans_map.find(keyst) == ans_map.end()) {
ans_map.insert(pair<string,vector<string> >(keyst, vector<string>()));
}
ans_map[keyst].push_back(strs[i]);
}
map<string, vector<string>>::iterator iter;
for(iter = ans_map.begin(); iter != ans_map.end(); iter++) {
ans.push_back(iter->second);
}
return ans;
}
};