| 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: | $str = trim($str); |
| 19: | |
| 20: | if (empty($str)) { |
| 21: | return false; |
| 22: | } |
| 23: | |
| 24: | $length = mb_strlen($str); |
| 25: | $tree = &$this->tree; |
| 26: | |
| 27: | for ($i = 0; $i < $length; $i++) { |
| 28: | $char = $str[$i]; |
| 29: | $is_end = $i === ($length - 1); |
| 30: | |
| 31: | if (!isset($tree['child'][$char])) { |
| 32: | $tree['child'][$char] = [ |
| 33: | 'data' => '', |
| 34: | 'child' => [] |
| 35: | ]; |
| 36: | } |
| 37: | |
| 38: | if ($is_end) { |
| 39: | $tree['child'][$char]['data'] = (string) $data; |
| 40: | } |
| 41: | |
| 42: | $tree = &$tree['child'][$char]; |
| 43: | } |
| 44: | } |
| 45: | |
| 46: | |
| 47: | public function search($str) { |
| 48: | } |
| 49: | |
| 50: | |
| 51: | public function search_data($str) { |
| 52: | $str = trim($str); |
| 53: | |
| 54: | if (empty($str)) { |
| 55: | return false; |
| 56: | } |
| 57: | |
| 58: | $length = mb_strlen($str); |
| 59: | $tree = &$this->tree; |
| 60: | |
| 61: | for ($i = 0; $i < $length; $i++) { |
| 62: | $char = $str[$i]; |
| 63: | $is_end = $i === ($length - 1); |
| 64: | |
| 65: | if (!isset($tree['child'][$char])) { |
| 66: | return false; |
| 67: | } |
| 68: | |
| 69: | if ($is_end) { |
| 70: | return $tree['child'][$char]['data'] ?? ''; |
| 71: | } |
| 72: | |
| 73: | $tree = &$tree['child'][$char]; |
| 74: | } |
| 75: | } |
| 76: | } |
| 77: | |