49. Group Anagrams(unsolved)

来源:互联网 发布:ftp传输数据的具体方式 编辑:程序博客网 时间:2024/05/22 11:32

Given an array of strings, group anagrams together.

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

[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]

class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        unordered_map<string,multiset<string>> mp;        for(auto s:strs)        {            string t=s;            sort(t.begin(),t.end());            mp[t].insert(s);        }        vector<vector<string>> result;        for(auto m:mp)        {            vector<string> res(m.second.begin(),m.second.end());            result.push_back(res);        }        return result;    }};

解答:
主要是multiset 是什么意思。还有就是mp[t].insert(s); 中的mp[t]是value,t是key,所以insert是multiset的方法。

Multiple-key set
Multisets are containers that store elements following a specific order, and where multiple elements can have equivalent values.

In a multiset, the value of an element also identifies it (the value is itself the key, of type T). The value of the elements in a multiset cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container.

Internally, the elements in a multiset are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

multiset containers are generally slower than unordered_multiset containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

Multisets are typically implemented as binary search trees.

std::multiset::insert

Internally, multiset containers keep all their elements sorted following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering.

二刷时,发现这种做法更好

class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        unordered_map<string,vector<string>> str;        vector<vector<string>> res;        for(string s:strs)        {            string temp=s;            sort(s.begin(),s.end());            str[s].push_back(temp);        }        for(auto a:str)        {            res.push_back(a.second);        }        return res;    }};
0 0
原创粉丝点击