Last active
September 22, 2022 13:59
-
-
Save deepakkumarnd/823b8abf0d7785da47e0ec160757f8b1 to your computer and use it in GitHub Desktop.
Trie.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Trie | |
attr_accessor :hash, :value | |
def initialize | |
@hash = Array.new(26) { nil } | |
@value = nil | |
end | |
def insert(new_word) | |
word = new_word.downcase | |
if !contains?(word) | |
temp = self | |
prev = self | |
word.each_char do |c| | |
prev = temp | |
i = to_index(c) | |
temp = @hash[i] || (@hash[i] = Trie.new) | |
end | |
prev.value = word | |
end | |
end | |
def contains?(word) | |
temp = self | |
word.downcase! | |
word.each_char do |c| | |
i = to_index(c) | |
if @hash[i].nil? | |
return false | |
else | |
temp = @hash[i] | |
end | |
end | |
temp.has_word? | |
end | |
def has_word? | |
!value.nil? | |
end | |
def to_index(c) | |
c.ord - 'a'.ord | |
end | |
end | |
trie = Trie.new | |
p trie.insert("parrot") | |
p trie.insert("google") | |
p trie.contains?("facebook") | |
p trie.contains?("answer") | |
p trie.contains?("googl") | |
p trie.insert("monogram") | |
p trie.contains?("parrot") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment