LeetCode 49. Group Anagrams

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85239954

题目链接:字母异位词分组 - 力扣 (LeetCode)

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.


相同的一组单词就是sort之后是相同的字典序
使用一个哈希表做分组

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> hash;
        for(auto s : strs){ //如果这里用auto &s的话,原数组会改变!
            string rs = s;
            sort(s.begin(), s.end());
            hash[s].push_back(rs);
        }
        
        vector<vector<string>> res;
        for(auto & group : hash){  //加引用会更快
            res.push_back(group.second);
        }
        return res;
    }
};

没有更多推荐了,返回首页