vault backup: 2022-09-06 17:14:03

This commit is contained in:
juan 2022-09-06 17:14:03 +08:00
parent 77b57a8131
commit ae0ea5e170

View file

@ -4,7 +4,7 @@
> ##### Data structures: > ##### Data structures:
> >
> #DS #array #hash_table > #DS #array #hash_table #two_way_hash_table
> >
> ##### Difficulty: > ##### Difficulty:
> >
@ -34,18 +34,24 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ
**Example 1:** **Example 1:**
```
**Input:** strs = ["eat","tea","tan","ate","nat","bat"] **Input:** strs = ["eat","tea","tan","ate","nat","bat"]
**Output:** [["bat"],["nat","tan"],["ate","eat","tea"]] **Output:** [["bat"],["nat","tan"],["ate","eat","tea"]]
```
**Example 2:** **Example 2:**
```
**Input:** strs = [""] **Input:** strs = [""]
**Output:** [[""]] **Output:** [[""]]
```
**Example 3:** **Example 3:**
```
**Input:** strs = ["a"] **Input:** strs = ["a"]
**Output:** [["a"]] **Output:** [["a"]]
```
#### Constraints #### Constraints
@ -58,7 +64,10 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ
> [!summary] > [!summary]
> This is a #hash_table problem. > 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 - ana2id: turn anagram into an id
- id2str: turn id into strings that has the anagrams - 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, Note that vectors doesn't work in unordered hash maps,
unless we use custom hash functions. 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 ### Solution
Two way hash table
```cpp ```cpp
class Solution { class Solution {
public: public:
@ -109,4 +131,8 @@ public:
return id2str; return id2str;
} }
}; };
``` ```
Counting sort
#TODO: solve using counting sort