-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.php
145 lines (93 loc) · 2 KB
/
trie.php
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php
Class TrieNode {
public $children,$end;
public function __construct() {
$this->children = array();
$this->end = false;
}
}
Class Trie {
private $root;
public function __construct() {
$this->root = new TrieNode;
}
public function Insert($string) {
$length = strlen($string);
if(!$length) {
throw Exception("Invalid String");
}
$tempNode = $this->root;
for($i=0;$i<$length;$i++) {
if(isset($tempNode->children[$string[$i]])) {
$tempNode = $tempNode->children[$string[$i]];
} else {
$tempNode->children[$string[$i]] = new TrieNode();
$tempNode = $tempNode->children[$string[$i]];
}
}
$tempNode->end = true;
return true;
}
public function Search($string) {
$tempNode = $this->searchNode($string);
if(!$tempNode) {
return false;
}
if($tempNode->end) {
return true;
}
return false;
}
public function isPrefix($string) {
$tempNode = $this->searchNode($string);
if($tempNode) {
return true;
} else {
return false;
}
}
private function searchNode($string) {
$length = strlen($string);
if(!$length) {
throw Exception("Invalid String");
}
$tempNode = $this->root;
for($i=0;$i<$length;$i++) {
if(isset($tempNode->children[$string[$i]])) {
$tempNode = $tempNode->children[$string[$i]];
} else {
return NULL;
}
}
return $tempNode;
}
public function FindLargestPrefix($string) {
$length = strlen($string);
if(!$length) {
throw Exception("Invalid String");
}
$tempNode = $this->root;
for($i=0;$i<$length;$i++) {
if(isset($tempNode->children[$string[$i]])) {
$tempNode = $tempNode->children[$string[$i]];
} else {
if($i) {
return substr($string,0,$i);
} else {
return NULL;
}
}
}
return $string;
}
}
$trie = new Trie;
$trie->Insert("geeks");
$search = 'geek';
if($trie->isPrefix($search)) {
echo "$search is a prefix\n";
} else {
echo "$search is not a prefix\n";
}
echo $trie->FindLargestPrefix($search)."\n";
?>