Created
May 21, 2011 12:44
-
-
Save Pet3ris/984490 to your computer and use it in GitHub Desktop.
A simple trie
This file contains 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
module Spellchecker | |
class Trie | |
attr_reader :kids | |
attr_accessor :terminal | |
def initialize() | |
@kids = Hash.new | |
@terminal = false | |
end | |
# Add word to the trie | |
def add(word) | |
if word != "" | |
cur = self | |
word.downcase.each_char do |character| | |
cur.kids[character] = Trie.new if not cur.kids.has_key? character | |
cur = cur.kids[character] | |
end | |
cur.terminal = true | |
end | |
end | |
# Check if word is in trie | |
def has_word?(word) | |
cur = self | |
word.each_char do |character| | |
return false if not cur.kids.has_key? character | |
cur = cur.kids[character] | |
end | |
cur.terminal | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment