49. Group Anagrams

problem description

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.

algorithm thought

找出有相同字符,顺序不一样的所有字符串,然后返回他们的集合。这里有一种最简单的办法确定-sort。将所有的字符串sort一下,排序之后相等的字符串,就可以认定为一个group。

code

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string,vector<string>> ma;
        for(int i=0;i<strs.size();++i){
            string co=strs[i];
            sort(co.begin(),co.end());
            if(ma.count(co)){
                ma[co].push_back(strs[i]);
            }
            else{
                ma[co]=vector<string>({strs[i]});
            }

        }
        vector<vector<string>> res;
        for(auto& m:ma){
            res.push_back(m.second);
        }
        return res;
    }
};

algorithm analysis

假定有n个字符串,每个字符串平均长度是m,对每个字符排序时间复杂度是O(nlgn),两个字符串比较时间复杂度是O(n),然后需要定义一个hashmap保存之前遍历的字符串的结果。最后时间复杂度是O(m*nlgn)

Last updated