Skip to content

Instantly share code, notes, and snippets.

@valarpirai
Created January 31, 2023 13:14
Show Gist options
  • Save valarpirai/eb397947d653c74905e0cdc4f4c14556 to your computer and use it in GitHub Desktop.
Save valarpirai/eb397947d653c74905e0cdc4f4c14556 to your computer and use it in GitHub Desktop.
Design Add and Search Words Data Structure
class TrieNode
attr_accessor :childrens, :leaf
def initialize
self.childrens = {}
self.leaf = false
end
end
class WordDictionary
def initialize
@root = TrieNode.new
end
def addWord(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
end
def search(word)
temp = @root
puts dfs(temp, word, 0)
end
def dfs(node, word, index)
if 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("bad")
wordDictionary.addWord("dad")
wordDictionary.addWord("mad")
wordDictionary.search("pad")
wordDictionary.search("bad")
wordDictionary.search("mad")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment