Skip to content

Instantly share code, notes, and snippets.

@dudo
Created September 22, 2021 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudo/2881bf42db33c5783ab5fe22be1dcd33 to your computer and use it in GitHub Desktop.
Save dudo/2881bf42db33c5783ab5fe22be1dcd33 to your computer and use it in GitHub Desktop.
require 'set'
module Trie
class T9
attr_reader :root
def initialize
@root = Hash.new
end
def build(word = '')
node = root
t9numbers = word.tr('a-z', '22233344455566677778889999')
t9numbers.each_char do |ch|
node[ch] ||= Hash.new
node = node[ch]
end
node['end'] ||= Set.new
node['end'].add(word)
end
def find(t9numbers = '')
node = root
t9numbers.each_char do |ch|
return [] unless node = node[ch]
end
node['end'].to_a
end
end
end
@dudo
Copy link
Author

dudo commented Sep 22, 2021

trie = Trie::T9.new
trie.build('foo')
trie.build('bar')
trie.build('foo')
trie.build('fom')
trie.find('366')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment