- Group Anagrams
Given an array of strings, group anagrams together.
Example
Example 1:
Input:
[“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
Output:
[[“ate”,“eat”,“tea”],
[“bat”],
[“nat”,“tan”]]
Example 2:
Input:
[“eat”,“nowhere”]
Output:
[[“eat”],
[“nowhere”]]
Notice
All inputs will be in lower-case.
解法1:我用的map of map。
注意:
1)返回一个空的2D vector可以用{{}}。
2) map的first和second都不能加(),即不能用first(),直接用first就可。
代码如下:
class Solution {
public:
/**
* @param strs: the given array of strings
* @return: The anagrams which have been divided into groups
*/
vector<vector<string>> groupAnagrams(vector<string> &strs) {
int n = strs.size();
vector<vector<string>> result;
if (n == 0) return {{}};
map<map<char, int>, vector<string>> mp;
for (int i = 0; i < n; ++i) {
map<char, int> dict;
int m = strs[i].size();
for (int j = 0; j < m; ++j) {
dict[strs[i][j]]++;
}
mp[dict].push_back(strs[i]);
}
for (auto m : mp) {
result.push_back(m.second);
}
return result;
}
};
二刷: 注意我们可以把vector 用string来表示,从而简化代码,当然这个string是会显示乱码,不过我们只需要用它在map里面做第一项来处理就可以了。
//string(freqTable.begin(), freqTable.end())
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
int n = strs.size();
//map<vector<int>, vector<string>> mp; //<freqTable, vector<string>>
map<string, vector<string>> mp; //<string, vector<string>>
for (auto str : strs) {
vector<int> freqTable(26, 0);
for (auto c : str) {
freqTable[c - 'a']++;
}
mp[string(freqTable.begin(), freqTable.end())].push_back(str);
}
for (auto freq : mp) {
res.push_back(freq.second);
}
return res;
}
};
本文介绍了一种用于将字符串数组中所有字谜(anagrams)进行分组的高效算法。通过使用map结构,算法能够快速识别并分组具有相同字符组成的字符串,即使在大规模数据集上也能保持良好的性能。
762





