Skip to content

Commit 54e88a3

Browse files
committed
adding TRIE data structure in PHP
1 parent 8002426 commit 54e88a3

File tree

4 files changed

+100
-0
lines changed

4 files changed

+100
-0
lines changed

DS/Tree/.DS_Store

6 KB
Binary file not shown.

DS/Tree/Classes/Trie.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
/*
4+
* Author: Mizanur Rahman <[email protected]>
5+
*
6+
*/
7+
8+
namespace DS\Tree\Classes;
9+
10+
use DS\Tree\Classes\TrieNode;
11+
12+
class Trie
13+
{
14+
public $root;
15+
public function __construct()
16+
{
17+
$this->root = new TrieNode;
18+
}
19+
20+
public function insert(string $key)
21+
{
22+
$key = strtolower($key);
23+
$length = strlen($key);
24+
$pCrawl = $this->root;
25+
for ($level = 0; $level < $length; $level++) {
26+
$index = ord($key[$level]) - ord('a');
27+
if (is_null($pCrawl->children[$index]))
28+
$pCrawl->children[$index] = new TrieNode();
29+
30+
$pCrawl = $pCrawl->children[$index];
31+
}
32+
$pCrawl->isEndOfWord = true;
33+
}
34+
35+
public function search(string $key)
36+
{
37+
$key = strtolower($key);
38+
$length = strlen($key);
39+
$pCrawl = $this->root;
40+
for ($level = 0; $level < $length; $level++) {
41+
$index = ord($key[$level]) - ord('a');
42+
if (is_null($pCrawl->children[$index]))
43+
return false;
44+
45+
$pCrawl = $pCrawl->children[$index];
46+
}
47+
return (!is_null($pCrawl) && $pCrawl->isEndOfWord);
48+
}
49+
}

DS/Tree/Classes/TrieNode.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* Author: Mizanur Rahman <[email protected]>
5+
*
6+
*/
7+
8+
namespace DS\Tree\Classes;
9+
10+
class TrieNode
11+
{
12+
public $children;
13+
public $isEndOfWord;
14+
const ALPHABETSIZE = 26;
15+
16+
public function __construct()
17+
{
18+
$this->isEndOfWord = false;
19+
$this->children = array_fill(0,self::ALPHABETSIZE, null);
20+
}
21+
}

DS/Tree/Examples/trie.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* Author: Mizanur Rahman <[email protected]>
5+
*
6+
*/
7+
8+
include __DIR__ . '/../../../Vendor/Autoload.php';
9+
10+
use \DS\Tree\Classes\Trie;
11+
12+
try {
13+
$keys = ["dhaka", "bangladesh", "there", "answer", "any", "by", "bye", "their"];
14+
15+
$trie = new Trie();
16+
// Construct trie
17+
for ($i = 0; $i < count($keys); $i++)
18+
$trie->insert($keys[$i]);
19+
20+
$searches = ["dhaka", "three", "these", "there", "the", "any", "DHAKA", "anyone", "desh"];
21+
foreach ($searches as $search) {
22+
if ($trie->search($search)) {
23+
echo "$search - is present in the trie \n";
24+
} else {
25+
echo "$search - is not present in the trie \n";
26+
}
27+
}
28+
} catch (Exception $e) {
29+
echo $e->getMessage();
30+
}

0 commit comments

Comments
 (0)