A trie (pronounced "try") is a type of search tree that is used to store dynamic sets or associative arrays where the keys are usually strings. It allows for efficient retrieval of keys in a dataset, making it particularly useful for tasks like autocomplete and spell-checking.
Below is a simple implementation of a trie in Swift:
// Trie Node Definition
class TrieNode {
var children: [Character: TrieNode] = [:]
var isEndOfWord: Bool = false
}
class Trie {
private var root: TrieNode
init() {
root = TrieNode()
}
// Insert a word into the trie
func insert(_ word: String) {
var node = root
for char in word {
if node.children[char] == nil {
node.children[char] = TrieNode()
}
node = node.children[char]!
}
node.isEndOfWord = true
}
// Search for a word in the trie
func search(_ word: String) -> Bool {
var node = root
for char in word {
if let nextNode = node.children[char] {
node = nextNode
} else {
return false
}
}
return node.isEndOfWord
}
// Check if any word in the trie starts with the given prefix
func startsWith(_ prefix: String) -> Bool {
var node = root
for char in prefix {
if let nextNode = node.children[char] {
node = nextNode
} else {
return false
}
}
return true
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?