万普插件库

jQuery插件大全与特效教程

字母异位词分组

字母异位词分组

  • 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
}
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言