You are viewing a single comment's thread. Return to all comments →
Simple Ruby Trie OOP solution:
class Contacts def initialize @root = ContactNode.new end def add(name) node = @root name.each_char do |c| idx = c2i(c) node.children[idx] = ContactNode.new if node.children[idx].nil? node = node.children[idx] node.count += 1 end end def find_count(partial) node = @root partial.each_char do |c| idx = c2i(c) return 0 if node.children[idx].nil? node = node.children[idx] end node.count end private def c2i(c) c.ord - 'a'.ord end end class ContactNode attr_accessor :count, :children def initialize(alphasize = 26) @count = 0 @children = Array.new(alphasize) end end contacts = Contacts.new gets.to_i.times do op, arg = gets.split case op when 'add' contacts.add(arg) when 'find' puts contacts.find_count(arg) end end
Seems like cookies are disabled on this browser, please enable them to open this website
Tries: Contacts
You are viewing a single comment's thread. Return to all comments →
Simple Ruby Trie OOP solution: