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

TrieTree::add()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 19
rs 8.8571
cc 5
eloc 13
nc 5
nop 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
}