Problem Description:
Given a string array, ectopic word letters together. Ectopic word letters refer to the same letters, but arranged in different strings.
Example:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Description:
- All inputs are lowercase letters.
- The order of the answers that were not considered.
The basic idea:
String in ascending order as a key. To be grouped as a vector type value.
AC Code:
class Solution {
public:
string ChangeOrder(string str) {
// 返回字符升序排序的字符串
string res;
map<char, int> hashmap;
for (char ch : str) {
++hashmap[ch];
}
// 按照自然顺序遍历
for (char ch = 'a'; ch <= 'z'; ++ch) {
for (int i = 0; i < hashmap[ch]; ++i) {
res += ch;
}
}
return res;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> hashmap;
for (string str : strs) {
hashmap[ChangeOrder(str)].push_back(str);
}
vector<vector<string>> res;
for (auto it = hashmap.begin(); it != hashmap.end(); ++it) {
res.push_back(it->second);
}
return res;
}
};
Daniel's ideas:
The above code we spent quite a long time to pass a string copy.
Rather all results stored in the hashmap, then copy the results one by one to the vector.
As a direct operation vector. hashmap is stored in our vector related information.
(Here is the number of rows stored in the vector)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,int>index;
vector<vector<string>> result;
for(auto i:strs)
{
//sort(i.begin();i.end());
string tmp = i;
sort(tmp.begin(),tmp.end());
if(index.find(tmp)==index.end())
{
index.insert({tmp,(int)result.size()});
result.push_back(vector<string>{i});
}
else
{
result[index[tmp]].push_back(i);
}
}
return result;
}
};
Other experience:
- You may wish to directly operate on the result set returned , so when you create a copy of a waste of space .
- I sort each character string using a counting sorting method, in fact, we use sort will be more efficient.
- We can use hashmap to group, in which the key is to mark our group. value is a collection of group members .