[LeetCode] 49. Group Anagrams 群组错位词

 

Given an array of strings, group anagrams together.html

Example:java

Input: ,
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]["eat", "tea", "tan", "ate", "nat", "bat"]

Note:git

  • All inputs will be in lowercase.
  • The order of your output does not matter.

 

这道题让咱们群组给定字符串集中全部的错位词,所谓的错位词就是两个字符串中字母出现的次数都同样,只是位置不一样,好比 abc,bac, cba 等它们就互为错位词,那么如何判断二者是不是错位词呢,能够发现若是把错位词的字符顺序从新排列,那么会获得相同的结果,因此从新排序是判断是否互为错位词的方法,因为错位词从新排序后都会获得相同的字符串,以此做为 key,将全部错位词都保存到字符串数组中,创建 key 和当前的不一样的错位词集合个数之间的映射,这里之因此没有创建 key 和其隶属的错位词集合之间的映射,是用了一个小 trick,从而避免了最后再将 HashMap 中的集合拷贝到结果 res 中。当检测到当前的单词不在 HashMap 中,此时知道这个单词将属于一个新的错位词集合,因此将其映射为当前的错位词集合的个数,而后在 res 中新增一个空集合,这样就能够经过其映射值,直接找到新的错位词集合的位置,从而将新的单词存入结果 res 中,参见代码以下:github

 

解法一:数组

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        unordered_map<string, int> m;
        for (string str : strs) {
            string t = str;
            sort(t.begin(), t.end());
            if (!m.count(t)) {
                m[t] = res.size();
                res.push_back({});
            }
            res[m[t]].push_back(str);
        }
        return res;
    }
};

 

下面这种解法没有用到排序,用一个大小为 26 的 int 数组来统计每一个单词中字符出现的次数,而后将 int 数组转为一个惟一的字符串,跟字符串数组进行映射,这样就不用给字符串排序了,参见代码以下:post

 

解法二:url

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        unordered_map<string, vector<string>> m;
        for (string str : strs) {
            vector<int> cnt(26);
            string t;
            for (char c : str) ++cnt[c - 'a'];
            for (int i = 0; i < 26; ++i) {
                if (cnt[i] == 0) continue;
                t += string(1, i + 'a') + to_string(cnt[i]);
            }
            m[t].push_back(str);
        }
        for (auto a : m) {
            res.push_back(a.second);
        }
        return res;
    }
};

 

相似题目:spa

https://github.com/grandyang/leetcode/issues/49code

 

相似题目:htm

Valid Anagram

Group Shifted Strings 

 

参考资料:

https://leetcode.com/problems/group-anagrams/

https://leetcode.com/problems/group-anagrams/discuss/19176/share-my-short-java-solution

https://leetcode.com/problems/group-anagrams/discuss/19200/10-lines-76ms-easy-c-solution-updated-function-signature

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索