Skip to content

Instantly share code, notes, and snippets.

@valarpirai
Created January 31, 2023 13:26
Show Gist options
  • Save valarpirai/192c3a0054efe3720e9b48e497d038de to your computer and use it in GitHub Desktop.
Save valarpirai/192c3a0054efe3720e9b48e497d038de to your computer and use it in GitHub Desktop.
class TrieNode
attr_accessor :childrens, :leaf
def initialize
self.childrens = {}
self.leaf = false
end
end
class WordDictionary
def initialize
@root = TrieNode.new
end
def add_word(word)
return if word.length < 0 || word.length > 25
temp = @root
word.each_char do |c|
temp.childrens[c] ||= TrieNode.new
temp = temp.childrens[c]
end
temp.leaf = true if temp.childrens.empty?
end
def search(word)
temp = @root
puts dfs(temp, word, 0)
dfs(temp, word, 0)
end
def dfs(node, word, index)
if word[index] == "."
node.childrens.each do |k, child|
return true if child.leaf && index == word.length - 1
return dfs(child, word, index + 1)
end
elsif node.childrens.key?(word[index])
child = node.childrens[word[index]]
return true if child.leaf && index == word.length - 1
return dfs(child, word, index + 1)
end
false
end
end
wordDictionary = WordDictionary.new
["WordDictionary","addWord","addWord","addWord","addWord","search","search","addWord","search","search","search","search","search","searc"].each do |word|
wordDictionary.add_word(word)
end
wordDictionary.search("pad")
wordDictionary.search("bad")
wordDictionary.search("s..rch")
wordDictionary.search("search")
wordDictionary.search(".ad")
wordDictionary.search("b..")
wordDictionary.search("c..")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment