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.
方法1:给每一个字符串排序,边排序边插入到map中,以排好序的字符串为key。遍历map将字符串向量导入到结果中。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
map<string,vector<string>> strsmap;
for(string str: strs){
string t=str;
sort(str.begin(),str.end());
strsmap[str].push_back(t);
}
for(auto a:strsmap){
res.push_back(a.second);
}
return res;
}
};
写法较复杂的方式:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<string> strs1(strs);
vector<vector<string>> res;
int n=strs1.size();
for(int i=0;i<n;i++){
sort(strs1[i].begin(),strs1[i].end());
}
map<string,vector<string>> strsMap;
for(int y=0;y<n;y++){
if(strsMap.count(strs1[y])==0)
strsMap.insert({strs1[y],{strs[y]}});
else
strsMap[strs1[y]].push_back(strs[y]);
}
for(auto w: strsMap){
res.push_back(w.second);
}
return res;
}
};
参考:
点击打开链接