ImplementTriePrefixTree   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
eloc 24
c 2
b 0
f 0
dl 0
loc 50
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A startsWith() 0 12 3
A search() 0 12 3
A __construct() 0 3 1
A insert() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TrieNode;
8
9
class ImplementTriePrefixTree
10
{
11
    /** @var \leetcode\util\TrieNode */
12
    private $root;
13
14
    public function __construct()
15
    {
16
        $this->root = new TrieNode();
17
    }
18
19
    public function insert(string $word): void
20
    {
21
        /** @var \leetcode\util\TrieNode $node */
22
        $node = $this->root;
23
        for ($i = 0, $n = strlen($word); $i < $n; $i++) {
24
            $value = $word[$i];
25
            if (!isset($node->children[$value])) {
26
                $node->children[$value] = new TrieNode($value);
27
            }
28
            $node = $node->children[$value];
29
        }
30
        $node->isWord = true;
31
    }
32
33
    public function search(string $prefix): bool
34
    {
35
        $node = $this->root;
36
        for ($i = 0, $n = strlen($prefix); $i < $n; $i++) {
37
            $value = $prefix[$i];
38
            if (!isset($node->children[$value])) {
39
                return false;
40
            }
41
            $node = $node->children[$value];
42
        }
43
44
        return $node->isWord;
45
    }
46
47
    public function startsWith(string $prefix): bool
48
    {
49
        $node = $this->root;
50
        for ($i = 0, $n = strlen($prefix); $i < $n; $i++) {
51
            $value = $prefix[$i];
52
            if (!isset($node->children[$value])) {
53
                return false;
54
            }
55
            $node = $node->children[$value];
56
        }
57
58
        return true;
59
    }
60
}
61