【问题标题】:Why trie is also called "prefix tree"?为什么 trie 也被称为“前缀树”?
【发布时间】:2013-09-28 09:36:21
【问题描述】:

我在阅读 Wikipedia 上的 this 文章时偶然发现了“trie 也称为前缀树”这一行。

我知道 trie 的用法,但为什么叫它“前缀树”?

【问题讨论】:

  • 如果在否决问题时人们可以给出原因或者至少他们可以给出一些相似的链接会更好。
  • 来自同一篇文章:“因为它们可以通过前缀进行搜索”。
  • 所以如果你的意思是如果我有 'te' 作为前缀,我可以找到所有组合,例如 'tea' 、 'ten' 、 'ted' 。我说得对吗?跨度>
  • 是的。您可以轻松找到所有以 'te' 开头的字符串。

标签: data-structures tree trie recursive-datastructures


【解决方案1】:

因为它们可以通过前缀进行搜索。您还可以反转 trie 并找到通配符:http://phpir.com/tries-and-wildcards

例如,学术一词是 c-i-m-e-d-a-c-a。使用相同的 和以前一样的技术,我们现在可以搜索所有以 a 结尾的单词 某些短语,允许我们在开头处理通配符 查询词,例如*学术上。

<?php
function buildTries($words) {
        $trie = new Trie();
        $rtrie = new Trie();
        foreach($words as $word) {
                $trie->add($word);
                $rtrie->add(strrev($word));
        }
        return array('trie' => $trie, 'rtrie' => $rtrie);
}

function searchTries($search, $tries) {
        $terms = explode('*', $search);
        if(count($terms) > 2) {
                return false;
        }

        if(strlen($terms[0]) && strlen($terms[0])) {
                // middle wildcard
                $straight = $tries['trie']->prefixSearch($terms[0]);
                $rev = $tries['rtrie']->prefixSearch(strrev($terms[1]));
                return array_intersect($straight, reverseArray($rev));
        } else if(strlen($terms[1]) ) {
                // leading wildcard
                return reverseArray($tries['rtrie']->prefixSearch(strrev($terms[1])));
        } else {
                // trailing wildcard
                return $tries['trie']->prefixSearch($terms[0]);
        }
}

function reverseArray($keys) {
        $return = array();
        foreach($keys as $key => $value) {
                $return[strrev($key)] = $value;
        }
        return $return;
}

/* Do some searches */

$words = array( 
        'adder',
        'addled',
        'abject',
        'agreement',
        'astronaut',
        'handily', 
        'happily',
        'helpfully'
);
$tries = buildTries($words);

$return = searchTries('h*ly', $tries);
var_dump($return);

$return = searchTries('ha*ly', $tries);
var_dump($return);
?>

两个 var 转储的结果如下所示:

array(3) {
  ["handily"]=>
  NULL
  ["happily"]=>
  NULL
  ["helpfully"]=>
  NULL
}

array(2) {
  ["handily"]=>
  NULL
  ["happily"]=>
  NULL
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2010-12-13
    • 1970-01-01
    • 2021-11-23
    • 2011-01-30
    • 1970-01-01
    相关资源
    最近更新 更多