
题目链接
Description
Given an array of strings, group anagrams together.
Example:
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,”eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
解题思路
题目要求对一组字符串进行分组,将字符串中字符相同只是顺序不同的字符串分到同一组。考虑利用map,首先对每个字符串进行排序,排序后应该被分到同一组的字符串结果相同,利用map做查找和分组。
示例代码
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, int> strmap;
int num = 0;
vector<vector<string>> res;
for (int i = 0; i < strs.size(); i++)
{
string tmp = strs[i];
sort(strs[i].begin(), strs[i].end());
if (strmap.count(strs[i]) == 1)
{
int index = strmap[strs[i]];
res[index].push_back(tmp);
}
else
{
vector<string> tmpvec;
tmpvec.push_back(tmp);
res.push_back(tmpvec);
strmap.insert(pair<string, int>(strs[i],num));
num++;
}
}
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
return res;
}




近期评论