Skip to content

Commit

Permalink
code 23
Browse files Browse the repository at this point in the history
  • Loading branch information
chenlixin93 committed Sep 30, 2020
1 parent 8f25823 commit ad43c00
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions 23刷题路线/[基础]208.实现-trie-前缀树.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Trie {
* Initialize your data structure here.
*/
function __construct() {
$this->root = new TrieNode();
$this->root = new TrieNode(); // 构建根节点
}

/**
Expand All @@ -32,9 +32,9 @@ function insert($word) {
if ($p->children[$index] == null) {
$p->children[$index] = new TrieNode();
}
$p = $p->children[$index];
$p = $p->children[$index]; // 移动到子节点
}
$p->is_word = true;
$p->is_word = true; // 当前单词走完一遍,标记is_word为真
}

/**
Expand All @@ -44,7 +44,7 @@ function insert($word) {
*/
function search($word) {
$node = $this->find($word);
return $node != null && $node->is_word;
return $node != null && $node->is_word; // 查找单词比较严格,必须is_word为真
}

/**
Expand All @@ -54,14 +54,14 @@ function search($word) {
*/
function startsWith($prefix) {
$node = $this->find($prefix);
return $node != null;
return $node != null; // 前缀存在即可
}

function find($prefix) {
$p = $this->root;
for ($i=0; $i < strlen($prefix); $i++) {
$index = (int)(ord($prefix[$i]) - ord('a'));
if ($p->children[$index] == null) return null;
if ($p->children[$index] == null) return null; // 找不到就返回 null
$p = $p->children[$index];
}
return $p;
Expand All @@ -73,7 +73,7 @@ class TrieNode {
public $children;

function __construct() {
$this->children = array_fill(0, 26, null); // 预留 26 个节点的空间
$this->children = array_fill(0, 26, null); // 预留 26 个节点的空间,因为字符范围在 a-z 之间
$this->is_word = false;
}
}
Expand Down

0 comments on commit ad43c00

Please sign in to comment.