Trie tree essence, is the use of the common prefix character string between the combined repeated prefix
The process of constructing the Trie time consuming for a set of strings of n characters, it is necessary to traverse all characters corresponding to the time complexity is O (n), but once constructed, the query efficiency is high, if the matching string the length is k, the k needs to be matched to the bird, not related to the original primary sequence, the corresponding time complexity is O (k), is substantially constant level number.
Scenario:
1. sensitive word filtering
2. Lenovo search box
PHP
class TrieNode
{
public $value;
public $children = [];
public $isEnd = false;
public function __construct($value)
{
$this->value = $value;
}
}
class Trie
{
public $root;
public function __construct()
{
$this->root = new TrieNode('/');
}
public function add($str)
{
$len = mb_strlen($str);
$parent = $this->root;
for ($i = 0; $i < $len; $i++) {
if ($parent->children[$str[$i]] == null) {
$parent->children[$str[$i]] = new TrieNode($str[$i]);
}
$parent = $parent->children[$str[$i]];
}
$parent->isEnd = true;
}
public function search($str)
{
$len = mb_strlen($str);
$parent = $this->root;
for ($i = 0; $i < $len; $i++) {
if ($parent->children[$str[$i]]->value != $str[$i]) {
return false;
}
$parent = $parent->children[$str[$i]];
}
return $parent->isEnd;
}
}
$strArr = [
'tom',
'tomhaha',
'tom2333',
'jack'
];
$trie = new Trie;
foreach ($strArr as $str) {
$trie->add($ str);
}
var_dump($trie->search('tom'));
GO
package main
import (
"fmt"
)
type TreeNode struct {
value string
isEnd bool
children map[rune]*TreeNode
}
func main() {
strArr := []string{"tom", "tom2333", "tomhaha", "jack"}
root := newTreeNode("/")
for _, s := range strArr {
root.add(s)
}
fmt.Println(root.search("tomhaha"))
}
func (node *TreeNode) add(str string) {
current := node
for _,s := range str {
if current.children[s] == nil {
current.children[s] = newTreeNode(string(s))
}
current = current.children[s]
}
current.isEnd = true
}
func (node *TreeNode) search(str string) bool {
current := node
for _,s := range str {
if current.children[s].value != string(s) {
return false
}
current = current.children[s]
}
return current.isEnd
}
func newTreeNode(value string) *TreeNode {
return &TreeNode{
value: value,
isEnd: false,
children: make(map[rune]*TreeNode),
}
}