字母异位词分组C++

字母异位词分组

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]

代码如下:

class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        unordered_map> hashmap;
        for(auto s : strs){//遍历strs中的每一个字符串
            string temp = s;
            sort(temp.begin(), temp.end());//字母相同的字符串排完序之后结果相同
            hashmap[temp].push_back(s);
        }
        int len = hashmap.size();
        vector> ans(len);//存放结果
        int index = 0;
        for(auto i : hashmap){
            ans[index] = i.second;
            ++ index;
        }
        return ans;
    }
};

解释如下:

对于原字符串数组中的每一个字符串,通过sort对其排序,具有相同元素的字符串排序结果必然相同,再将排序过后的字符串作为hash的key,每一个排完序相同的字符串进入同一个字符串数组,也就是相同key值对应的字符串数组,这就是这个算法的核心思想。

你可能感兴趣的:(字母异位词分组C++)