首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么trie又叫“前缀树”?

为什么trie又叫“前缀树”?
EN

Stack Overflow用户
提问于 2013-09-28 09:36:21
回答 1查看 761关注 0票数 1

我在维基百科上读到了的文章,无意中发现了这句话:"trie也叫前缀树“。

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

EN

回答 1

Stack Overflow用户

发布于 2013-09-28 09:45:47

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

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

代码语言:javascript
复制
<?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转储的结果如下所示:

代码语言:javascript
复制
array(3) {
  ["handily"]=>
  NULL
  ["happily"]=>
  NULL
  ["helpfully"]=>
  NULL
}

array(2) {
  ["handily"]=>
  NULL
  ["happily"]=>
  NULL
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19065474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档