We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Thanksbitmalloc!Thisworksgreatwithrubyforalltests:#!/bin/rubyclassTrieNodeattr_accessor:char,:words_count,:children,:is_worddefinitialize(char=nil,is_word=false)@char=char@words_count=0# num of words this prefix is a part of@children=[]@is_word=is_wordenddefget_child(c)forchildin@childrenifchild.char==creturnchildendendreturnnilendend# end TrieNode classclassTriedefinitialize@root=TrieNode.new("*")enddefaddwordcurr=@rootword.chars.eachdo|w|next_node=curr.get_child(w)ifnext_node==nilnext_node=TrieNode.new(w)curr.children<<next_nodeendnext_node.words_count+=1curr=next_nodeendcurr.is_word=trueenddeffindprefixcurr=@rootprefix.chars.eachdo|c|next_node=curr.get_child(c)ifnext_node==nilputs"0";return# prefix not foundendcurr=next_nodeendputscurr.words_countendend# end class Triet=Trie.newn=gets.strip.to_ifora0in(0..n-1)instructions=gets.strip.split(' ')t.add(instructions[1])ifinstructions[0]=="add"t.find(instructions[1])ifinstructions[0]=="find"end
Tries: Contacts
You are viewing a single comment's thread. Return to all comments →