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
這道題讓咱們羣組給定字符串集中全部的錯位詞,所謂的錯位詞就是兩個字符串中字母出現的次數都同樣,只是位置不一樣,好比 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
參考資料:
https://leetcode.com/problems/group-anagrams/
https://leetcode.com/problems/group-anagrams/discuss/19176/share-my-short-java-solution