Last active
March 4, 2020 12:45
-
-
Save kzkn/9d6efaff598fc2c19a65df97eb4ba1e5 to your computer and use it in GitHub Desktop.
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
class WordDictionary | |
def initialize | |
@root = Node.new | |
end | |
def add_word(word) | |
@root.add_word(word, 0) | |
end | |
def search(word) | |
@root.search(word, 0) | |
end | |
class Node | |
def add_word(word, idx) | |
if word.size == idx | |
@complete = true | |
return | |
end | |
ch = word[idx] | |
child = children[ch] | |
unless child | |
child = Node.new | |
children[ch] = child | |
end | |
child.add_word(word, idx + 1) | |
end | |
def search(word, idx) | |
return found? if word.size == idx | |
ch = word[idx] | |
if ch == '.' | |
children.values.any? { |child| child.search(word, idx + 1) } | |
else | |
child = children[ch] | |
!child.nil? && child.search(word, idx + 1) | |
end | |
end | |
def children | |
@children ||= {} | |
end | |
def found? | |
!!@complete | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment