Trie¶
| Spice | |
|---|---|
Trie struct¶
A trie (also called prefix tree) is a data structure that stores a set of strings in a way that makes prefix-based lookups efficient. Every edge is labeled with a single character, so a word corresponds to a path from the root down to a node marked as the end of a word. Words that share a common prefix also share the nodes that spell out that prefix.
Time complexity (k = length of the word/prefix):
Insert: O(k)
Contains: O(k)
Starts with: O(k)
Remove: O(k)
Constructors¶
ctor¶
| Spice | |
|---|---|
Construct an empty trie
ctor¶
| Spice | |
|---|---|
Construct a trie as a deep copy of another trie
Parameters
| Name | Type | Description |
|---|---|---|
original |
const Trie& |
Trie to copy |
dtor¶
| Spice | |
|---|---|
Destruct the trie, freeing all allocated nodes
Methods¶
insert¶
| Spice | |
|---|---|
Insert a word into the trie. Inserting a word that is already present has no effect.
Parameters
| Name | Type | Description |
|---|---|---|
word |
string |
The word to insert |
contains¶
| Spice | |
|---|---|
Check if the trie contains the given word.
Parameters
| Name | Type | Description |
|---|---|---|
word |
string |
The word to look for |
Returns: bool — True if the exact word was inserted before, false otherwise
startsWith¶
| Spice | |
|---|---|
Check if the trie contains any word that starts with the given prefix. The empty prefix is contained in every trie.
Parameters
| Name | Type | Description |
|---|---|---|
prefix |
string |
The prefix to look for |
Returns: bool — True if at least one stored word starts with the prefix, false otherwise
countWordsWithPrefix¶
| Spice | |
|---|---|
Count how many stored words start with the given prefix.
Parameters
| Name | Type | Description |
|---|---|---|
prefix |
string |
The prefix to look for |
Returns: unsigned long — Number of stored words that start with the prefix
remove¶
| Spice | |
|---|---|
Remove a word from the trie. Removing a word that is not present has no effect. Nodes that become unused after the removal are pruned and their memory is freed.
Parameters
| Name | Type | Description |
|---|---|---|
word |
string |
The word to remove |
getSize¶
| Spice | |
|---|---|
Get the number of words stored in the trie.
Returns: unsigned long — The number of stored words
isEmpty¶
| Spice | |
|---|---|
Check if the trie is empty.
Returns: bool — True if no words are stored, false otherwise
clear¶
| Spice | |
|---|---|
Remove all words from the trie, freeing all nodes but the root.
Operators¶
operator=¶
| Spice | |
|---|---|
Copy-assign another trie into this one, replacing all currently stored words
Parameters
| Name | Type | Description |
|---|---|---|
other |
const Trie& |
Trie to copy from |