TypePHP 编译器 https://swoole.com/aot/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

75 lines
1.4 KiB

--TEST--
mixed: 2
--FILE--
<?php
class Node
{
public $is_end = false;
public $child = [];
}
class Trie
{
private $root = null;
function __construct()
{
$this->root = new Node();
}
function insert($word)
{
$node = $this->root;
for ($i = 0; $i < strlen($word); $i++) {
if (!isset($node->child[$word[$i]])) {
$node->child[$word[$i]] = new Node();
}
$node = $node->child[$word[$i]];
if ($i == strlen($word) - 1) {
$node->is_end = true;
}
}
}
function search($word)
{
$node = $this->root;
for ($i = 0; $i < strlen($word); $i++) {
if (isset($node->child[$word[$i]])) {
$node = $node->child[$word[$i]];
} else {
return false;
}
}
return $node->is_end;
}
function startsWith($prefix)
{
$node = $this->root;
for ($i = 0; $i < strlen($prefix); $i++) {
if (isset($node->child[$prefix[$i]])) {
$node = $node->child[$prefix[$i]];
} else {
return false;
}
}
return true;
}
}
function main()
{
$Trie = new Trie();
$Trie->insert('apple');
var_dump($Trie->search("apple"));
var_dump($Trie->startsWith("apps"));
}
?>
--EXPECT--
bool(true)
bool(false)