最近我遇到了一个编码挑战,我不得不在PHP中构建一个简单的trie,我设法使用php和foreach循环来完成它, m对代码本身并不满意(看起来并不像它应该的那样),所以我试图用php的迭代器来实现它。通过复杂的多维数组迭代(PHP上的Trie数据结构,代码改进)
所以,我有一个复杂的数组(线索),例如:
array(
'a' => array(),
'b' => array(
'a' => array(
'c' => array(
'o' => array(
'n' => array()
)
)
)
),
'x' => array(
'x' => array(
'x' => array()
)
)
);
我要检查,如果“培根”这是存储在此线索一句话,过程中找到它应该是通过迭代遍历数组,并检查它是嵌套和存在的每个节点,例如:我需要在根中的元素与键'b',然后在阵列数组[[b']),我需要检查是否存在数组['b'] ['a'],然后['b'] ['a'] ['c']等等。
使用foreach循环,我可以通过引用传递新数组并通过引用来检查密钥。现在使用一个迭代器似乎我锤炼了一些代码(以及做foreachs php复制数组时,使我认为这个解决方案可能使用比使用迭代器更多的内存)的事实。
因此,代码到现在为止它已经条件完成while循环上不能在该停止(当前数组没有我搜索键)或成功(这是完整的字):
// OUTSIDE THE LOOP
$finished = false;
$string = 'bacon';
$string = str_split($string);
$queue = new SplQueue();
// Enqueue all the letters to the queue -> skipping this because it's boring
// FIRST WHILE LOOP
$iterator = new ArrayIterator($array);
$iterator->key(); // No match with queue -> check next key
// SECOND WHILELOOP
$iterator->next();
$iterator->key(); // Matches with the key I want do dequeue (B),
$next = new ArrayIterator($array[$iterator->key()]);
$queue->dequeue();
// THIRD WHILE LOOP
$next->key(); // Match [A] -> create new iterator
$next = new ArrayIterator($next[$next->key()]);
$queue->dequeue();
// 4TH WHILE LOOP
$next->key(); // Match [C] -> create new iterator
$next = new ArrayIterator($next[$next->key()]);
$queue->dequeue();
// 5TH WHILE LOOP
$next->key(); // Match [O] -> create new iterator
$next = new ArrayIterator($next[$next->key()]);
$queue->dequeue();
// 5TH WHILE LOOP
$next->key(); // Match [N]
$next = new ArrayIterator($next[$next->key()]);
$queue->dequeue(); // queue empty, throw success
所以,直到现在,这是我的,但事实上,我在每个循环上创建一个新的ArrayIterator它困扰着我,所以我希望能听到有人对此问题有更好的解决方案。
在此先感谢。
如果代码已经工作,你可能会有更好的运气在https://codereview.stackexchange.com/ – Chris