Givenan array of strings, group anagrams together.
Forexample, given: ["eat", "tea", "tan","ate", "nat", "bat"],
Return:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
这题记住很重要的几点能够非常快的解题,
首先unordered_map是哈希表,查询速度为O(1),其实map的key可以为string,也可以为其他值,这题很明显是查找所有拥有相同stringkey的string集合,所以可以将数组中每一个排序之后的string作为key,将其所对应的string集合作为value,直接使用哈希表能够非常快的得到结果
以后在做在数组中统计所有相同的值的个数或者是要求输出所有相同的值的时候可以直接使用unordered_map解决!
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> theStore;
string tmp;
for (int i = 0; i < strs.size(); i++)
{
tmp = strs[i];
sort(tmp.begin(), tmp.end());
theStore[tmp].push_back(strs[i]);
}
vector<vector<string>> result;
for (auto it = theStore.begin(); it != theStore.end(); it++)
{
result.push_back(it->second);
}
return result;
}
};
这题做的我心累,首先需要注意的是当在循环里面重复声明数组的时候,实际上数组指针会重用,如果你不使用类似于={0}的方法来初始化的话,重新声明的数组会使用上一个声明的数组指针,这个时候假如你将数组指针赋值给了其他的部分,那么这个时候会出错,所以这个时候要记得使用指针=new int()的方式来声明!
以后要记住,尽量少用memset(sizeof(p)),这里的p是指针,这种方法在某种情况下是错误的!
class Solution {
public:
int checkInCharsStore(vector<int *> &theCharsStore, int * p)
{
for (int i = 0; i < theCharsStore.size(); i++)
{
int j = 0;
for (j = 0; j < 26; j++)
{
if (theCharsStore[i][j] != p[j])
break;
}
if (j == 26)
{
return i;
}
}
return -1;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<int *> theCharsStore;
vector<vector<string>> result;
vector<string> tmp;
for (int i = 0; i < strs.size(); i++)
{
int * p=new int[26];
memset(p, 0, sizeof(int)*26);
for (auto u : strs[i])
p[u - 'a']++;
int l = checkInCharsStore(theCharsStore, p);
if (l == -1)
{
tmp.clear(); tmp.push_back(strs[i]);
result.push_back(tmp);
theCharsStore.push_back(p);
}
else
{
result[l].push_back(strs[i]);
}
}
return result;
}
};