美文网首页
49. Group Anagrams

49. Group Anagrams

作者: yunmengze | 来源:发表于2018-10-09 22:45 被阅读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.


这道题可以将单词排序作为字典的键,然后取出字典的值即可。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        unordered_map<string, vector<string>> strMap;
        for(auto str : strs){
            string temp = str;
            sort(temp.begin(), temp.end());
            strMap[temp].push_back(str);
        }
        for(auto group : strMap){
            res.push_back(group.second);
        }
        return res;
    }
};

相关文章

网友评论

      本文标题:49. Group Anagrams

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