Tire主要包含两个操作,一个是将字符串集合构造成 Trie 树。这个过程分解开来的话,就是一个将字符串插入到 Trie 树的过程。另一个是在 Trie 树中查询一个字符串。
Trie 树是个多叉树,在这里用数组来存储一个节点的所有子结点。
Trie树节点类,PHP代码实现:
<?php
class TrieNode
{
public $data;
public $children = [];
public $isEndingChar = false;
public function __construct($data)
{
$this->data = $data;
}
}
Trie树
<?php
class Trie {
private $root;
public function __construct() {
$this->root = new TrieNode('/'); //根节点
}
public function getRoot() {
return $this->root;
}
public function insert($text) {
$p = $this->root;
for ($i = 0; $i < mb_strlen($text); $i++) {
$index = $data = $text[$i];
if (empty($p->children[$index])) {
$newNode = new TrieNode($data);
$p->children[$index] = $newNode;
}
$p = $p->children[$index];
}
$p->isEndingChar = true;
}
public function find($pattern) {
$p = $this->root;
for ($i = 0; $i < mb_strlen($pattern); $i++) {
$index = $pattern[$i];
if (empty($p->children[$index])) {
return false;
}
$p = $p->children[$index];
}
return $p->isEndingChar;
}