Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 21:53
Show Gist options
  • Save evidanary/6fe0f4dbb3c4c645c5e954403a599ffd to your computer and use it in GitHub Desktop.
Save evidanary/6fe0f4dbb3c4c645c5e954403a599ffd to your computer and use it in GitHub Desktop.
# Implement a Trie using hash (You need to first figure out what operations the trie has to support)
# add, contains, word_count, remove, etc.
class Trie
attr_accessor :root
def initialize()
@root = {}
end
# returns false if already present
def add(str)
cur = @root
new_word = false
str.chars.each do |c|
if !cur[c]
cur[c] = {}
new_word = true
end
cur = cur[c]
end
if !cur["end"]
cur["end"] = {}
new_word = true
end
new_word
end
def contains(word)
cur = @root
word.chars.each do |c|
return false if !cur[c]
cur = cur[c]
end
cur["end"]
end
end
t = Trie.new
t.add("abc")
t.add("ab")
t.add("abc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment