| 1: | <?php |
| 2: | |
| 3: | namespace nightmare; |
| 4: | |
| 5: | class trie |
| 6: | { |
| 7: | |
| 8: | public $tree; |
| 9: | |
| 10: | public function __construct() { |
| 11: | $this->tree = [ |
| 12: | 'data' => '', |
| 13: | 'child' => [] |
| 14: | ]; |
| 15: | } |
| 16: | |
| 17: | public function add($str, $data = '') { |
| 18: | $length = mb_strlen($str); |
| 19: | |
| 20: | if (!$length) { |
| 21: | return false; |
| 22: | } |
| 23: | |
| 24: | $tree = &$this->tree; |
| 25: | $chars = mb_str_split($str); |
| 26: | $i = 0; |
| 27: | |
| 28: | foreach ($chars as $char) { |
| 29: | $i++; |
| 30: | $is_end = $i === $length; |
| 31: | |
| 32: | if (!isset($tree['child'][$char])) { |
| 33: | $tree['child'][$char] = [ |
| 34: | 'data' => '', |
| 35: | 'child' => [] |
| 36: | ]; |
| 37: | } |
| 38: | |
| 39: | if ($is_end) { |
| 40: | $tree['child'][$char]['data'] = (string) $data; |
| 41: | } |
| 42: | |
| 43: | $tree = &$tree['child'][$char]; |
| 44: | } |
| 45: | } |
| 46: | |
| 47: | |
| 48: | public function search($str) { |
| 49: | $length = mb_strlen($str); |
| 50: | |
| 51: | if (!$length) { |
| 52: | return false; |
| 53: | } |
| 54: | |
| 55: | $tree = &$this->tree; |
| 56: | $chars = mb_str_split($str); |
| 57: | $i = 0; |
| 58: | |
| 59: | foreach ($chars as $char) { |
| 60: | $i++; |
| 61: | $is_end = $i === $length; |
| 62: | |
| 63: | if (!isset($tree['child'][$char])) { |
| 64: | return false; |
| 65: | } |
| 66: | |
| 67: | if ($is_end) { |
| 68: | return [ |
| 69: | 'data' => $tree['child'][$char]['data'] ?? '', |
| 70: | 'is_end' => count($tree['child'][$char]['child']) === 0 |
| 71: | ]; |
| 72: | } |
| 73: | |
| 74: | $tree = &$tree['child'][$char]; |
| 75: | } |
| 76: | } |
| 77: | } |
| 78: | |