-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path211.php
More file actions
102 lines (90 loc) · 2.26 KB
/
211.php
File metadata and controls
102 lines (90 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
class WordDictionary
{
public $root;
/**
* Initialize your data structure here.
*/
function __construct()
{
$this->root = new TrieNode();
}
/**
* Adds a word into the data structure.
* @param String $word
* @return NULL
*/
function addWord($word)
{
if (!$word) return;
$node = $this->root;
for ($i = 0; $i < strlen($word); $i ++) {
if (!isset($node->children[$word[$i]])) {
$node->children[$word[$i]] = new TrieNode($word[$i]);
}
$node = $node->children[$word[$i]];
}
$node->is_word = true;
}
/**
* Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
* @param String $word
* @return Boolean
*/
function search($word)
{
if (!$word) return true;
$node = $this->root;
return $this->searchRec($word, $node, 0);
}
/**
* @param $word
* @param TrieNode $node
* @param $pos
* @return boolean
*/
private function searchRec($word, $node, $pos)
{
if ($pos == strlen($word)) return $node->is_word;
if ($word[$pos] == '.') {
$pos ++;
foreach ($node->children as $child) {
if ($this->searchRec($word, $child, $pos)) {
return true;
}
}
return false;
} else {
if (!isset($node->children[$word[$pos]])) return false;
}
return $this->searchRec($word, $node->children[$word[$pos]], $pos + 1);
}
}
class TrieNode
{
public $children = [];
public $is_word = false;
public $val = null;
function __construct($val = null)
{
$this->val = $val;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* $obj = WordDictionary();
* $obj->addWord($word);
* $ret_2 = $obj->search($word);
*/
$obj = new WordDictionary();
$obj->addWord('at');
$obj->addWord('and');
$obj->addWord('an');
$obj->addWord('add');
var_export($obj);
var_dump($obj->search('a'));
var_dump($obj->search('.at'));
$obj->addWord('bat');
var_export($obj);
var_dump($obj->search('.at'));
var_dump($obj->search('b..'));