class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> Map;
for (auto &x: strs) {
vector<int> cnt(26, 0);
for (auto &y: x) cnt[y - 'a'] += 1;
string str = "";
for (auto &c: cnt) {
if (c == 0) str += "000";
else if (c < 10) str += "00" + to_string(c);
else if (c < 100) str += "0" + to_string(c);
else str += to_string(c);
}
Map[str].push_back(x);
}
vector<vector<string>> res;
for (auto &x: Map) {
res.push_back(x.second);
}
return res;
}
};
Time Complexity: O(n)
Space: O(n)
先計算出每個單字的字母出現數量,再將數量轉換成字串放入 Map 中,最終就可以知道有那些組了。