LeetCode49,字母异位分词组
题目
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
我的解答
- 使用一个multimap<string,string>,键为每个字符串经排序后的字符串,值为原字符串,例如“bca“保存为<“abc”,“bca”>。将每一个字符串放入map中。
- 遍历map,将键相同的元素放入同一组,即可。
- 附代码。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
multimap<string,string> m;
for(auto &s:strs)
{
string temp=s;
sort(temp.begin(),temp.end());
m.insert(make_pair(temp,s));
}
vector<vector<string>> result;
auto beg=m.begin();
auto end=m.end();
while(beg!=end)
{
string temp=(*beg).first;
vector<string> agroup;
agroup.push_back((*beg).second);
++beg;
while((*beg).first==temp)
{
temp=(*beg).first;
agroup.push_back((*beg).second);
++beg;
}
result.push_back(agroup);
}
return result;
}
};
大佬的解法
- 使用一个unordered_map<string,int>,键为每个字符串经排序后的字符串,值为目前已经出现的不同的字符串的数量。
- 遍历原容器,对每个字符串,先排序,在map中查找排序后的字符串。如果找到了,则根据值n,将原字符串存入结果中第n-1个组中。如果没找到,++num,存为新的键值对,将原字符串存入结果第num-1个组中。
与我的解法相比:
- 大佬的解法使用unordered_map,减少了管理map顺序的开销。
- map中只需要存组的个数的元素,而我的要存所有的元素。
- 只需遍历一次原容器,并在map中进行少量查找。我的需要遍历一次原容器,一次map,并且涉及到额外的字符串比较操作。
- 附代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ret_vect;
unordered_map<string,int> record;
string DNA;
int num =0;
for(int i=0;i<strs.size();i++){
DNA = strs[i];
sort(DNA.begin(),DNA.end());
if(record.find(DNA)==record.end()){
record[DNA] = ++num;
ret_vect.push_back(vector<string>(1,strs[i]));
}
else
ret_vect[record[DNA]-1].push_back(strs[i]);
}
return ret_vect;
}
};
这篇博客探讨了LeetCode49题目的解决方案,即如何将字母异位词分组。作者提供了两种解法,一种是使用multimap,另一种是使用unordered_map。通过对比,解释了大佬解法的优势在于减少开销并优化了内存管理。

被折叠的 条评论
为什么被折叠?



