-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path208.php
More file actions
93 lines (79 loc) · 1.92 KB
/
Copy path208.php
File metadata and controls
93 lines (79 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
class Trie
{
public $root;
/**
* Initialize your data structure here.
*/
function __construct()
{
$this->root = new TrieNode();
}
/**
* Inserts a word into the trie.
* @param String $word
* @return NULL
*/
function insert($word)
{
if (!$word) return;
$node = $this->root;
for ($i = 0; $i < strlen($word); $i ++) {
if (!isset($node->children[$word[$i]])) {
$node->children[$word[$i]] = new TrieNode($word[$i]);
}
$node = $node->children[$word[$i]];
}
$node->is_word = true;
}
/**
* Returns if the word is in the trie.
* @param String $word
* @return Boolean
*/
function search($word)
{
$node = $this->root;
for ($i = 0; $i < strlen($word); $i ++) {
if (!isset($node->children[$word[$i]])) return false;
$node = $node->children[$word[$i]];
}
return $node->is_word;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param String $prefix
* @return Boolean
*/
function startsWith($prefix)
{
$node = $this->root;
for ($i = 0; $i < strlen($prefix); $i ++) {
if (!isset($node->children[$prefix[$i]])) return false;
$node = $node->children[$prefix[$i]];
}
return true;
}
}
class TrieNode
{
public $children = [];
public $is_word = false;
public $val = null;
function __construct($val = null)
{
$this->val = $val;
}
}
/**
* Your Trie object will be instantiated and called as such:
* $obj = Trie();
* $obj->insert($word);
* $ret_2 = $obj->search($word);
* $ret_3 = $obj->startsWith($prefix);
*/
$obj = new Trie();
$obj->insert('apple');
$ret_2 = $obj->search('apple');
$ret_3 = $obj->startsWith('app');
var_dump($obj, $ret_2, $ret_3);