网上闲逛的时候,看到一篇介绍Trie 的文章。写得很明了,让人有实现的冲动。我观察了一下,觉得Trie (读作/ˈtraɪ/) 不就是一个树状的hash吗?!
反正连接同一节点与其子节点的边是不同的,比如与根节点相连的边分别为:b, g, $,这不正好满足哈市
class Trie def initialize(tail = ‘</p>) @@tail = tail @trie = {@@tail => {}} end def insert(ary) ary.each do |word| next if word == @@tail letter = word[0].chr if @trie[letter] != nil @trie[letter].insert([word[1..-1]]) else t = Trie.new t.insert([word[1..-1]]) @trie[letter] = t end end end end t = Trie.new t.insert([‘big</p>, ‘bigger</p>, ‘bill</p>, ‘good</p>, ‘gosh</p>])
注意:’</p>其实是’$’。
如果打印出来会发现每个子节点都出现了’$’=>{},而我们期望的是只在叶节点出现。先不管了。
只有插入显然不够,怎么的也得有个查询吧:
class Trie def exist?(word) word == ‘</p> ? true : ((not @trie[word[0].chr].nil?) and @trie[word[0].chr].exist?(word[1..-1])) end end t = Trie.new t.insert([‘big</p>, ‘bigger</p>, ‘bill</p>, ‘good</p>, ‘gosh</p>]) p t.exist?(‘big</p>) #=> true
还差个显示的函数。慢慢完善吧^_^!!
P.S. 这几天一直在查有关Trie的资料,看到fuliang写的一篇Trie and suffix array,实现了Trie的打印函数。
P.P.S 有人写了个Python 版的实现。