[LeetCode]49. Group Anagrams

同组字符串

Posted by JinFei on February 12, 2020

题目描述

Given an array of strings, group anagrams together.

Example1:

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.

解题思路

  • 首先要注意到 找相同一组的,实质上是 排序之后 结果相同的
  • 我们将排序后与对应的集合作为一个pair,key为 排序后的字符串,value 为这个集合
  • 最后遍历这个映射关系表,push上步生成的 map-> value 即可
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> mmap;
        vector<vector<string>> res;
        for(auto s : strs){
            string sTemp = s;
            sort(sTemp.begin(), sTemp.end());
            if(mmap.count(sTemp) != 0){
                mmap[sTemp].push_back(s);
            }else{
                vector<string> v;
                v.push_back(s);
                mmap[sTemp] = v;
            }
        }
        for(unordered_map<string, vector<string>>::iterator iter = mmap.begin(); iter != mmap.end(); iter++){
            res.push_back(iter -> second);
        }
        return res;
    }
};