【LeetCode-哈希表/字符串】字母异位词分组

题目描述

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

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

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

思路

字母易位词排序后是相等的,例如teaeat排序后都是aet。所以我们可以定义一个哈希表unordered_map<string, vector<string>> hash,哈希表的键是排序后的字符串,对应的值是排序前为该键的字符串,例如hash["aet"] = ["tea", "eat"]。算法如下:

  • 遍历输入的字符串数组:
    • 将当前字符串排序,将排序后的字符串作为键,将排序前的字符串放到该键对应的 vector 当中;
  • 遍历哈希表,提取值作为答案。

代码如下:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        if(strs.empty()) return {};

        unordered_map<string, vector<string>> hash;
        for(int i=0; i<strs.size(); i++){
            string origin = strs[i];
            sort(strs[i].begin(), strs[i].end());
            hash[strs[i]].push_back(origin);
        }

        vector<vector<string>> ans;
        unordered_map<string, vector<string>>::iterator it = hash.begin();
        for(; it!=hash.end(); it++){
            ans.push_back(it->second);
        }
        return ans;
    }
};
  • 时间复杂度:O(n*mlogm)
    n 为输入数组的长度,m 为数组中字符串的最长长度。
  • 空间复杂度:O(nm)
posted @ 2020-05-14 21:53  Flix  阅读(156)  评论(0编辑  收藏  举报