PHP Programmer interview Baidu face Test

Source: Internet
Author: User

is said to be a Baidu PHP face test, has given an array:

$arr = Array (' B ' => ' A ', ' C ' => ' a ', ' E ' => ' B ', ' d ' => ' B ', ' F ' => ' C ', ' G ' => ' e ', ' h ' => ' f ');


Write an algorithm that completes the conversion to the following format:

array  (     ' a '  => array  (          ' B '  => array  (             ' E '  => array  (                 [0] =>  ' G ',              ),             [0] =>  ' d ',          ),          ' C '  =>  array  (             ' F '  =>  array  (                [0 ] =>  ' h ',             ),         ),     ) 


This structure should belong to a trie tree. At the time of writing, because I did not find the second parameter of the Array_keys () function (Khan one first), and then wrote the following method to achieve.

Function getsomething (& $arr, & $re,  $c = ")  {     $c  or    //Mark     set to True     while ($k when there is a key corresponding to $c  = array_

Search ($c,  $arr))  {    //Loop gets the key with the value $c.         getsomething ($arr,  $re [$c],  $k);     //        unset ($arr [$k]) until the last time there is no key corresponding;         //removal    This element is no longer used         $

flag = true;    &NBSP}     //the normal existing key before the flag is true   description, does not continue to generate the elements of the [0] subscript      if (!  $flag)  return  $re [] =  $c; }//Call getsomething ($arr,  $re,   ' a ');

The


, though a bit of a miracle, is at least implemented. Here is another solution for a netizen using Array_keys ():

function _array_keys ($k, $arr) {

$return = array ();

if ($ret = Array_keys ($arr, $k)) {

foreach ($ret as $v) {

if ($t = _array_keys ($v, $arr)) {

$return [$v] = $t;

else {

$return [] = $v;

}} return

$return;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.