{% tabs %} {% tab title="CPP" %}
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
unordered_map<string,vector<string>> m;
for (string s: strs) {
string t = s; // 新变量要declare
sort(t.begin(),t.end());
m[t].push_back(s);
}
// 这里就是再loop 一遍
for (auto p : m) {
ans.push_back(p.second);
}
return ans;
}
};
{% endtab %}
{% tab title="Python" %}
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if not strs:
return
from collections import defaultdict
## python 直接解压
dit = defaultdict(list)
for i in range(len(strs)):
s = "".join(sorted(strs[i]))
dit[s].append(strs[i])
return [*dit.values()]
{% endtab %} {% endtabs %}