LeetCode(49)Group Anagrams

时间:2022-07-10 08:35:52

题目

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],

Return:

[

[“ate”, “eat”,”tea”],

[“nat”,”tan”],

[“bat”]

]

Note:

For the return value, each inner list’s elements must follow the lexicographic order.

All inputs will be in lower-case.

分析

该题目要求是将给定的一组字符串数组,按照同构词(相同字母组成的单词)分类,每组单词按照字典排序。

这道题AC算法考察的主要是哈希的思想,这样才能保证时间在要求的范围内。

开始按照常规思路,几层循环,寻找同构词,保存。。。但是结果会出现Time Limited Exceed,下面将给出两种算法实现,供对比思考。

Time Limited Exceed 代码

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
if (strs.empty())
return vector<vector<string> >(); int len = strs.size(); vector<vector<string> > ret; for (int i = 0; i < len; i++)
{
vector<string > sv;
string tmp1 = strs[i];
sv.push_back(tmp1); sort(tmp1.begin(), tmp1.end());
for (int j = i + 1; j < len; j++)
{
string tmp2 = strs[j];
sort(tmp2.begin(), tmp2.end()); if (tmp1 == tmp2)
{
sv.push_back(strs[j]);
//将处理后的元素赋值为空
strs[j] = "";
}
}//for //按字典排序该序列
sort(sv.begin(), sv.end());
//添加到结果vector
ret.push_back(sv); }//for
return ret;
}
};

AC代码

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
if (strs.empty())
return vector<vector<string> >(); int len = strs.size(); //将字符串数组按照字典顺序排序
sort(strs.begin(), strs.end()); //存储结果
vector<vector<string> > ret; //利用哈希思想构建map,将排序后相等的字符串存在相应的vector
map<string, vector<string>> mv; for (int i = 0; i < len; i++)
{
string str = strs[i];
sort(str.begin(), str.end()); mv[str].push_back(strs[i]);
} for (map<string, vector<string> >::iterator iter = mv.begin(); iter != mv.end(); iter++)
ret.push_back(iter->second); return ret;
}
};

GitHub测试程序源码