[LeetCode] 49. Group Anagrams 群組錯位詞


 

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.

 

這道題讓我們群組給定字符串集中所有的錯位詞,所謂的錯位詞就是兩個字符串中字母出現的次數都一樣,只是位置不同,比如 abc,bac, cba 等它們就互為錯位詞,那么如何判斷兩者是否是錯位詞呢,可以發現如果把錯位詞的字符順序重新排列,那么會得到相同的結果,所以重新排序是判斷是否互為錯位詞的方法,由於錯位詞重新排序后都會得到相同的字符串,以此作為 key,將所有錯位詞都保存到字符串數組中,建立 key 和當前的不同的錯位詞集合個數之間的映射,這里之所以沒有建立 key 和其隸屬的錯位詞集合之間的映射,是用了一個小 trick,從而避免了最后再將 HashMap 中的集合拷貝到結果 res 中。當檢測到當前的單詞不在 HashMap 中,此時知道這個單詞將屬於一個新的錯位詞集合,所以將其映射為當前的錯位詞集合的個數,然后在 res 中新增一個空集合,這樣就可以通過其映射值,直接找到新的錯位詞集合的位置,從而將新的單詞存入結果 res 中,參見代碼如下:

 

解法一:

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 數組轉為一個唯一的字符串,跟字符串數組進行映射,這樣就不用給字符串排序了,參見代碼如下:

 

解法二:

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;
    }
};

 

Github 同步地址:

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

 

類似題目:

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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM