Class: DSA::Trie
- Inherits:
-
Object
- Object
- DSA::Trie
- Defined in:
- lib/dsa-ruby/trie.rb
Overview
DSA::Trie - A prefix tree (trie) data structure for string storage and lookup.
Efficient for prefix-based searches and word lookups.
Defined Under Namespace
Classes: Node
Instance Method Summary collapse
-
#delete(word) ⇒ Boolean
Deletes a word from the trie if it exists.
-
#initialize ⇒ DSA::Trie
constructor
Initialize a new empty trie.
-
#insert(word) ⇒ DSA::Trie
Inserts a word into the trie.
-
#search(word) ⇒ Boolean
Searches for an exact word in the trie.
-
#starts_with(prefix) ⇒ Boolean
Checks if any word in the trie starts with the given prefix.
Constructor Details
Instance Method Details
#delete(word) ⇒ Boolean
Deletes a word from the trie if it exists.
81 82 83 |
# File 'lib/dsa-ruby/trie.rb', line 81 def delete(word) delete_recursive(@root, word, 0) end |
#insert(word) ⇒ DSA::Trie
Inserts a word into the trie.
38 39 40 41 42 43 44 45 46 |
# File 'lib/dsa-ruby/trie.rb', line 38 def insert(word) node = @root word.each_char do |char| node.children[char] ||= Node.new node = node.children[char] end node.word_end = true self end |
#search(word) ⇒ Boolean
Searches for an exact word in the trie.
56 57 58 59 |
# File 'lib/dsa-ruby/trie.rb', line 56 def search(word) node = find_node(word) !!(node && node.word_end) end |
#starts_with(prefix) ⇒ Boolean
Checks if any word in the trie starts with the given prefix.
69 70 71 |
# File 'lib/dsa-ruby/trie.rb', line 69 def starts_with(prefix) !!find_node(prefix) end |