
C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> anagramMap;
for(string str : strs){
string sortedStr = str;
sort(sortedStr.begin(),sortedStr.end());
anagramMap[sortedStr].push_back(str);
}
vector<vector<string>>ans;
for(auto pair : anagramMap){
ans.push_back(pair.second);
}
return ans;
}
};
Python:
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
str_dict = {}
for s in strs:
sorted_s = ''.join(sorted(s))
if sorted_s not in str_dict:
str_dict[sorted_s] = []
str_dict[sorted_s].append(s)
return list(str_dict.values())
8万+

被折叠的 条评论
为什么被折叠?



