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 | class Trie{ public $tree = array (); public function insert( $str ){ $count = strlen ( $str ); $T = & $this ->tree; //关联数组递归各个字符,无则新建 for ( $i = 0; $i < $count ; $i ++){ $c = $str [ $i ]; if (!isset( $T [ $c ])) $T [ $c ] = array (); $T = & $T [ $c ]; } } public function remove( $chars ){ if ( $this ->find( $chars )){ $count = strlen ( $chars ); $T = & $this ->tree; for ( $i = 0; $i < $count ; $i ++){ $c = $chars [ $i ]; if ( count ( $T [ $c ]) == 1){ unset( $T [ $c ]); return true; } $T = & $T [ $c ]; } } } public function find( $chars ){ $count = strlen ( $chars ); $T = & $this ->tree; //循环遍历各个字符,如无则返回false for ( $i = 0; $i < $count ; $i ++){ $c = $chars [ $i ]; if (! array_key_exists ( $c , $T )){ return false; } $T = & $T [ $c ]; } //否则返回找到 return true; } } $t = new Trie(); $t ->insert( 'str' ); var_dump( $t ->find( 'str' )); |
更多:
https://github.com/fran6co/phptrie
http://kaiserleib.com/archives/63
http://www.cnblogs.com/endsock/p/3584161.html
标签:none
第9行 $chars 应该为 $str