49. Group Anagrams

来源:互联网 发布:美股数据下载 编辑:程序博客网 时间:2024/05/23 00:00

题目

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.

分析

将相同字母构成的字符串合并到一个vector中,利用构成字母相同这点构建索引,先将字符串排序,形成对应的索引,然后将原字符串放到map中保存,后续直接将map中的second保存到返回结果中即可。

class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        vector<vector<string>> res;        unordered_map<string, vector<string>> mp;        for(auto str:strs){//以排序后的字符串作为索引,在map中保存对应的原字符串            string temp=str;            sort(temp.begin(),temp.end());            mp[temp].push_back(str);        }        for(auto m:mp){//map中相同字母构成的字符串对应索引相同            res.push_back(m.second);        }        return res;    }};


原创粉丝点击