美文网首页
29. Anagrams

29. Anagrams

作者: 时光杂货店 | 来源:发表于2017-03-17 15:54 被阅读4次

    题目

    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
    Return:

    [
    ["ate", "eat","tea"],
    ["nat","tan"],
    ["bat"]
    ]

    Note: All inputs will be in lower-case.

    频度: 4

    解题之法

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            unordered_map<string, multiset<string>> mp;
            for (string s : strs) {
                string t = s; 
                sort(t.begin(), t.end());
                mp[t].insert(s);
            }
            vector<vector<string>> anagrams;
            for (auto m : mp) { 
                // 注意这种初始化方式
                vector<string> anagram(m.second.begin(), m.second.end());
                anagrams.push_back(anagram);
            }
            return anagrams;
        }
    };
    

    相关文章

      网友评论

          本文标题:29. Anagrams

          本文链接:https://www.haomeiwen.com/subject/boventtx.html