finding common prefix of array of strings

后端 未结 17 1701
一向
一向 2020-11-29 06:15

I have an array like this:

$sports = array(
\'Softball - Counties\',
\'Softball - Eastern\',
\'Softball - North Harbour\',
\'Softball - South\',
\'Softball -         


        
17条回答
  •  猫巷女王i
    2020-11-29 06:46

    I would use this:

    $prefix = array_shift($array);  // take the first item as initial prefix
    $length = strlen($prefix);
    // compare the current prefix with the prefix of the same length of the other items
    foreach ($array as $item) {
        // check if there is a match; if not, decrease the prefix by one character at a time
        while ($length && substr($item, 0, $length) !== $prefix) {
            $length--;
            $prefix = substr($prefix, 0, -1);
        }
        if (!$length) {
            break;
        }
    }
    

    Update   Here’s another solution, iteratively comparing each n-th character of the strings until a mismatch is found:

    $pl = 0; // common prefix length
    $n = count($array);
    $l = strlen($array[0]);
    while ($pl < $l) {
        $c = $array[0][$pl];
        for ($i=1; $i<$n; $i++) {
            if ($array[$i][$pl] !== $c) break 2;
        }
        $pl++;
    }
    $prefix = substr($array[0], 0, $pl);
    

    This is even more efficient as there are only at most numberOfStrings‍·‍commonPrefixLength atomic comparisons.

提交回复
热议问题