Skip to content

Instantly share code, notes, and snippets.

@hoffm
Created October 24, 2022 13:54
Show Gist options
  • Save hoffm/e190a0686ef3a958f7a2f8be4c18e60c to your computer and use it in GitHub Desktop.
Save hoffm/e190a0686ef3a958f7a2f8be4c18e60c to your computer and use it in GitHub Desktop.
class Trie < Hash
def initialize
# Ensure that this is not a special Hash by disallowing
# initialization options.
super
end
def add(string)
string.chars.inject(self) do |trie, char|
trie[char] ||= Trie.new
end
end
def longest_common_prefix
if keys.length == 1
char = keys.first
char + self[char].longest_common_prefix
else
''
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment