Created
July 7, 2015 03:01
-
-
Save howtomakeaturn/92df85e2f83a4c7d52e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function makeTrie($words) | |
{ | |
$end = '_end_'; | |
$root = []; | |
foreach($words as $word){ | |
$currentDict = &$root; | |
$charArray = preg_split('//u',$word, -1, PREG_SPLIT_NO_EMPTY); | |
foreach($charArray as $char){ | |
if(array_key_exists($char, $currentDict)){ | |
$currentDict = &$currentDict[$char]; | |
}else{ | |
$currentDict[$char] = []; | |
$currentDict = &$currentDict[$char]; | |
} | |
} | |
$currentDict[$end] = $end; | |
} | |
return $root; | |
} | |
public function inTrie($trie, $word) | |
{ | |
$end = '_end_'; | |
$currentDict = &$trie; | |
$charArray = preg_split('//u',$word, -1, PREG_SPLIT_NO_EMPTY); | |
foreach($charArray as $char){ | |
if(array_key_exists($char, $currentDict)){ | |
$currentDict = &$currentDict[$char]; | |
}else{ | |
return false; | |
} | |
} | |
if(array_key_exists($end, $currentDict)){ | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment