29. Anagrams

题目

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

你可能感兴趣的:(29. Anagrams)