Find length of initial segment matching mask on Arrays

后端 未结 2 1932
鱼传尺愫
鱼传尺愫 2021-01-23 07:18

Given an array with n values, for example:

$arr[] = \'ABCDEFABC\';
$arr[] = \'ABCDEFDEF\';
$arr[] = \'ABCDEFGHI\';
$arr[] = \'ABCDEFJKL\';

how

2条回答
  •  余生分开走
    2021-01-23 08:01

    If I understand correctly, you're trying to determine the set of longest common prefixes given a set of strings.

    Breaking it down, the shared prefix between any two strings may be found as

    function longestCommonPrefix($str1, $str2) {
      $minLen = min(strlen($str1), strlen($str2));
      for ($i = 0; $i < $minLen; $i++) {
          if ($str1[$i] != $str2[$i]) {
              return substr($str1, 0, $i);
          }
      }
      return substr($str1, 0, $minLen);
    }
    

    One way to get the set of prefixes could then be:

    function longestCommonPrefixes($arr) {
      sort($arr);
      $prefixes = array();
      for ($i = 0; $i < count($arr); $i++) {
          for ($j = $i+1; $j < count($arr); $j++) {
              $prefix = longestCommonPrefix($arr[$i], $arr[$j]);
              if ($prefix == "") break;
              $prefixes[$prefix] = true;
          }
      }
      return array_keys($prefixes);
    }
    

    Notice that the returned prefixes may be prefixes of each other. That is, it is possible for the result to contain a set of strings such as array('A', 'AA', 'AAA').

    Putting it all together:

    $arr = array();
    $arr[] = 'ABCDEFABC';
    $arr[] = 'ABCDEFDEF';
    $arr[] = 'ABCDEFGHI';
    $arr[] = 'ABCDEFJKL';
    $arr[] = 'DEFABCABC';
    $arr[] = 'DEFABCDEF';
    $arr[] = 'DEFABCGHI';
    $arr[] = 'DEFABCJKL';
    
    print_r(longestCommonPrefixes($arr));
    

    yields

    Array
    (
        [0] => ABCDEF
        [1] => DEFABC
    )
    

提交回复
热议问题