From ae0ea5e170645fe876dfe0a260696d32e2e43dc3 Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 6 Sep 2022 17:14:03 +0800 Subject: [PATCH] vault backup: 2022-09-06 17:14:03 --- OJ notes/pages/Leetcode Group-Anagrams.md | 32 ++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/OJ notes/pages/Leetcode Group-Anagrams.md b/OJ notes/pages/Leetcode Group-Anagrams.md index d859e21..a06f4f6 100644 --- a/OJ notes/pages/Leetcode Group-Anagrams.md +++ b/OJ notes/pages/Leetcode Group-Anagrams.md @@ -4,7 +4,7 @@ > ##### Data structures: > -> #DS #array #hash_table +> #DS #array #hash_table #two_way_hash_table > > ##### Difficulty: > @@ -34,18 +34,24 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ **Example 1:** +``` **Input:** strs = ["eat","tea","tan","ate","nat","bat"] **Output:** [["bat"],["nat","tan"],["ate","eat","tea"]] +``` **Example 2:** +``` **Input:** strs = [""] **Output:** [[""]] +``` **Example 3:** +``` **Input:** strs = ["a"] **Output:** [["a"]] +``` #### Constraints @@ -58,7 +64,10 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ > [!summary] > This is a #hash_table problem. -This one can be solved simply using two-way hash tables, consisting two hash tables: +#### Two way hash table + +This one can be solved simply using two-way hash tables, +consisting of two hash tables: - ana2id: turn anagram into an id - id2str: turn id into strings that has the anagrams @@ -74,8 +83,21 @@ CPP-style initialization of C's array. Note that vectors doesn't work in unordered hash maps, unless we use custom hash functions. +And arrays in c style definition (`int arr[26];`) will be +hashed according to address, not content. + +#### Alternative method + +By using sorted strings as keys, we can also solve this +problem. + +Since the input is lowercase English letters, counting +sort can be used. + ### Solution +Two way hash table + ```cpp class Solution { public: @@ -109,4 +131,8 @@ public: return id2str; } }; -``` \ No newline at end of file +``` + +Counting sort + +#TODO: solve using counting sort \ No newline at end of file