Skip to content

Instantly share code, notes, and snippets.

@prettymuchbryce
Created September 14, 2012 04:28
Show Gist options
  • Save prettymuchbryce/3719773 to your computer and use it in GitHub Desktop.
Save prettymuchbryce/3719773 to your computer and use it in GitHub Desktop.
Dictionary with Trie Tree
class Node
attr_accessor :endOfWord, :children
def initialize()
@endOfWord = false
@children = {}
end
end
class Dictionary
def initialize()
@roots = {}
end
def search(string)
if @roots[string[0]]
if string.length == 1 && @roots[string[0]].endOfWord
return true
end
return searchFor(string[1..-1],@roots[string[0]])
else
return false
end
end
def insert(string)
if !@roots[string[0]]
@roots[string[0]] = Node.new
end
insertWord(string[1..-1],@roots[string[0]])
end
private
def insertWord(string,node)
if node.children[string[0]]
nextChild = node.children[string[0]]
else
nextChild = Node.new
node.children[string[0]] = nextChild
end
if string.length==1
nextChild.endOfWord = true
return
else
insertWord(string[1..-1],nextChild)
end
end
def searchFor(string,node)
if string.length==0
if node.endOfWord
return true
else
return false
end
end
if node.children[string[0]]
return searchFor(string[1..-1],node.children[string[0]])
else
return false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment