Tetris-ing an array

后端 未结 16 1723
时光取名叫无心
时光取名叫无心 2021-01-30 15:38

Consider the following array:

/www/htdocs/1/sites/lib/abcdedd
/www/htdocs/1/sites/conf/xyz
/www/htdocs/1/sites/conf/abc/         


        
16条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 16:02

    Probably too naive and noobish but it works. I have used this algorithm:

     $intLargestSize ){
                        //remember this as the largest
                        $intLargestSize = $CSL[$i][$j]; 
                        //wipe any previous results
                        $ret = array();
                        //and then fall through to remember this new value
                    }
                    if( $CSL[$i][$j] == $intLargestSize )
                        //remember the largest string(s)
                        $ret[] = substr($str1, $i-$intLargestSize+1, $intLargestSize);
                }
                //else, $CSL should be set to 0, which it was already initialized to
            }
        }
        //return the list of matches
        return $ret;
    }
    
    
    $arr = array(
    '/www/htdocs/1/sites/lib/abcdedd',
    '/www/htdocs/1/sites/conf/xyz',
    '/www/htdocs/1/sites/conf/abc/def',
    '/www/htdocs/1/sites/htdocs/xyz',
    '/www/htdocs/1/sites/lib2/abcdedd'
    );
    
    // find the common substring
    $longestCommonSubstring = strlcs( $arr[0], $arr[1] );
    
    // remvoe the common substring
    foreach ($arr as $k => $v) {
        $arr[$k] = str_replace($longestCommonSubstring[0], '', $v);
    }
    var_dump($arr);
    

    Output:

    array(5) {
      [0]=>
      string(11) "lib/abcdedd"
      [1]=>
      string(8) "conf/xyz"
      [2]=>
      string(12) "conf/abc/def"
      [3]=>
      string(10) "htdocs/xyz"
      [4]=>
      string(12) "lib2/abcdedd"
    }
    

    :)

提交回复
热议问题