题意: 给一个字符串数组,将这个字符串按照组成的字母进行分组。
如
["eat", "tea", "tan", "ate", "nat", "bat"],
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
这里直接使用暴力法,通过使用map
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
//用来对strs进行分类,其中key值为每个字符串从小到大排的字符,value为vector
map<string,vector<string>> m;
for(int i=0;i<strs.size();i++)
{
string tmp=strs[i];
//排序
sort(tmp.begin(),tmp.end());
//插入到对应的vector上
m[tmp].push_back(strs[i]);
}
auto it=m.begin();
vector<vector<string>> re;
//对re进行赋值
while(it!=m.end())
{
re.push_back(it->second);
it++;
}
return re;
}
};
本文介绍了一种基于排序的字符串分组算法,用于解决给定字符串数组中字母组成相同但顺序不同的字符串分组问题。该算法利用了 map 结构,通过排序每个字符串并以其排序后的形式作为 key 值,原始字符串作为 value 存入 map 中,最终得到按字母组成分组的字符串集合。
6500

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



