Tetris-ing an array

后端 未结 16 1398
时光取名叫无心
时光取名叫无心 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条回答
  •  梦毁少年i
    2021-01-30 16:21

    You could remove prefix the fastest way, reading each character only once:

    function findLongestWord($lines, $delim = "/")
    {
        $max = 0;
        $len = strlen($lines[0]); 
    
        // read first string once
        for($i = 0; $i < $len; $i++) {
            for($n = 1; $n < count($lines); $n++) {
                if($lines[0][$i] != $lines[$n][$i]) {
                    // we've found a difference between current token
                    // stop search:
                    return $max;
                }
            }
            if($lines[0][$i] == $delim) {
                // we've found a complete token:
                $max = $i + 1;
            }
        }
        return $max;
    }
    
    $max = findLongestWord($lines);
    // cut prefix of len "max"
    for($n = 0; $n < count($lines); $n++) {
        $lines[$n] = substr(lines[$n], $max, $len);
    }
    

提交回复
热议问题