美文网首页
49. Group Anagrams/字母异位词分组

49. Group Anagrams/字母异位词分组

作者: 蜜糖_7474 | 来源:发表于2019-05-21 09:44 被阅读0次

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

Note:

All inputs will be in lowercase.
The order of your output does not matter.

AC代码

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> ans;
        map<string, vector<string>> mp;
        for (int i = 0; i < strs.size(); ++i) {
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());
            mp[tmp].push_back(strs[i]);
        }
        for (auto it = mp.begin(); it != mp.end(); ++it)
            ans.push_back(it->second);
        return ans;
    }
};

总结

相关文章

网友评论

      本文标题:49. Group Anagrams/字母异位词分组

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