字母异位词分组
- hash-map + vector,重点考察数据结构
C++实现
class Solution {
public:
vector<vector> groupAnagrams(vector& strs) {
// hash-map + vector
unordered_map<string, vector> mp;
for (const auto & str : strs) {
string key = str;
sort(key.begin(), key.end());
mp[key].emplace_back(str);
}
vector<vector> res;
for (const auto & e : mp) {
res.emplace_back(e.second);
}
return res;
}
};
golang实现
// hash-map + vector
mp := map[string][]string{}
for _, str := range strs {
tmp := []byte(str)
sort.Slice(tmp, func(i,j int) bool {
return tmp[i] < tmp[j]
})
key := string(tmp)
mp[key] = append(mp[key], str)
}
res := [][]string{}
for _, arr := range mp {
res = append(res, arr)
}
return res
}