Completed
Push — master ( 1bd80c...98c7c3 )
by Siro Díaz
02:10
created

TrieTree   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 9
c 1
b 1
f 0
lcom 2
cbo 1
dl 0
loc 43
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A numWords() 0 3 1
A size() 0 3 1
B add() 0 19 5
A count() 0 3 1
1
<?php
2
/**
3
 * DataStructures for PHP
4
 *
5
 * @link      https://github.com/SiroDiaz/DataStructures
6
 * @copyright Copyright (c) 2017 Siro Díaz Palazón
7
 * @license   https://github.com/SiroDiaz/DataStructures/blob/master/README.md (MIT License)
8
 */
9
namespace DataStructures\Trees;
10
11
use DataStructures\Trees\Nodes\TrieNode;
12
13
/**
14
 * TrieTree
15
 *
16
 * The TrieTree class is a trie (also called digital tree and sometimes radix tree or prefix tree)
17
 * that is used to get in O(m) being m the word length.
18
 * It is used in software like word corrector and word suggest.
19
 *
20
 * @author Siro Diaz Palazon <[email protected]>
21
 */
22
class TrieTree implements Countable {
23
    private $root;
24
    private $numWords;
25
    private $size;
26
    
27
    public function __construct() {
28
        $this->root = new TrieNode();
29
        $this->numWords = 0;
30
        $this->size = 0;
31
    }
32
33
    public function numWords() : int {
34
        return $this->numWords;
35
    }
36
37
    public function size() : int {
38
        return $this->size;
39
    }
40
41
    public function add($word) {
42
        $word = trim($word);
43
        if(mb_strlen($word) === 0) {
44
            return;
45
        }
46
47
        $current = &$this->root;
48
        for($i = 0; $i < mb_strlen($word); $i++) {
49
            $char = mb_substr($word, $i, 1, 'UTF-8');
50
            if(!isset($current->children[$char])) {
51
                if($i === mb_strlen($word) - 1) {
52
                    $current->children[$char] = new TrieNode($char, true);
53
                } else {
54
                    $current->children[$char] = new TrieNode($char, false);
55
                }
56
            }
57
            $current = &$current->children[$char];
58
        }
59
    }
60
61
    public function count() {
62
        return $this->size();
63
    }
64
}