Skip to content

Instantly share code, notes, and snippets.

@howtomakeaturn
Created July 7, 2015 03:01
Show Gist options
  • Save howtomakeaturn/92df85e2f83a4c7d52e9 to your computer and use it in GitHub Desktop.
Save howtomakeaturn/92df85e2f83a4c7d52e9 to your computer and use it in GitHub Desktop.
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