Created
November 16, 2010 21:28
-
-
Save chewbranca/702546 to your computer and use it in GitHub Desktop.
Find string permutations using a Trie
This file contains 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 | |
attr_accessor :value, :children | |
def initialize value = '' | |
@value = value | |
@children = {} | |
end | |
def [] val | |
@children[val] | |
end | |
def []= val, trie | |
@children[val] = trie | |
end | |
def next_val char | |
self.value + char | |
end | |
def to_s | |
puts @value unless @value.empty? | |
@children.each {|c| c.to_s } | |
nil | |
end | |
def self.build_trie str, root = nil | |
root ||= Trie.new | |
str.each_char do |char| | |
# To allow duplicates switch these lines | |
rest = str.delete char | |
#rest = str.sub char, '' | |
root[char] ||= Trie.build_trie(rest, Trie.new(root.next_val(char))) | |
end | |
root | |
end | |
end | |
Trie.build_trie('aac').to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment