Created
October 24, 2022 13:54
-
-
Save hoffm/e190a0686ef3a958f7a2f8be4c18e60c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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