| Total Complexity | 10 |
| Total Lines | 50 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 |
||
| 59 | } |
||
| 60 | } |
||
| 61 |