Tetris-ing an array

后端 未结 16 1389
时光取名叫无心
时光取名叫无心 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

    Perhaps porting the algorithm Python's os.path.commonprefix(m) uses would work?

    def commonprefix(m):
        "Given a list of pathnames, returns the longest common leading component"
        if not m: return ''
        s1 = min(m)
        s2 = max(m)
        n = min(len(s1), len(s2))
        for i in xrange(n):
            if s1[i] != s2[i]:
                return s1[:i]
        return s1[:n]
    

    That is, uh... something like

    function commonprefix($m) {
      if(!$m) return "";
      $s1 = min($m);
      $s2 = max($m);
      $n = min(strlen($s1), strlen($s2));
      for($i=0;$i<$n;$i++) if($s1[$i] != $s2[$i]) return substr($s1, 0, $i);
      return substr($s1, 0, $n);
    }
    

    After that you can just substr each element of the original list with the length of the common prefix as the start offset.

提交回复
热议问题