A generic trie implementation in Swift allows you to efficiently store a dynamic set of strings and perform prefix searches. Below is a simple implementation of a generic trie that can handle any type of comparable keys.
class TrieNode {
var children: [T: TrieNode] = [:]
var isEndOfWord: Bool = false
}
class Trie {
private let root = TrieNode()
func insert(word: [T]) {
var currentNode = root
for char in word {
if currentNode.children[char] == nil {
currentNode.children[char] = TrieNode()
}
currentNode = currentNode.children[char]!
}
currentNode.isEndOfWord = true
}
func search(word: [T]) -> Bool {
var currentNode = root
for char in word {
guard let nextNode = currentNode.children[char] else {
return false
}
currentNode = nextNode
}
return currentNode.isEndOfWord
}
func startsWith(prefix: [T]) -> Bool {
var currentNode = root
for char in prefix {
guard let nextNode = currentNode.children[char] else {
return false
}
currentNode = nextNode
}
return true
}
}
// Example Usage
let trie = Trie()
trie.insert(word: Array("apple".characters))
print(trie.search(word: Array("apple".characters))) // true
print(trie.startsWith(prefix: Array("app".characters))) // 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?