LeetCode——049

来源:互联网 发布:mac怎么卸载 编辑:程序博客网 时间:2024/06/07 13:52

这里写图片描述
/*
49. Group Anagrams My Submissions QuestionEditorial Solution
Total Accepted: 73397 Total Submissions: 267525 Difficulty: Medium
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:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.
Subscribe to see which companies asked this question

Show Tags
Show Similar Problems

*/

/*
解题思路:
使用map进行分类,将含有相同字母的字符串放到同一个集合中,判断是否含有相同字符,我们只需要将字符串进行排序然后作比较就可以了。最后遍历整个map取出各个集合,注意一点,各个小集合中的字符串是无序的,我们必须所有字符串排序,然后再将它放入到最终结果中。
*/

class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        //本题借助于hashmap        unordered_map<string,vector<string>> mp;        vector<vector<string>> res;        if(strs.size()==0)return res;        //分类        for(int i=0;i<strs.size();i++){            string s=strs[i];            sort(s.begin(),s.end());            mp[s].push_back(strs[i]);        }   //遍历取得结果        for(unordered_map<string,vector<string>>::iterator it=mp.begin();it!=mp.end();it++){            sort(it->second.begin(),it->second.end());            res.push_back(it->second);        }        return res;    }};
0 0