Efficient Algorithm for String Concatenation with Overlap

前端 未结 12 2221
轻奢々
轻奢々 2020-12-02 21:32

We need to combine 3 columns in a database by concatenation. However, the 3 columns may contain overlapping parts and the parts should not be duplicated. For example,

<
12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 21:54

    If you're doing it outside the database, try perl:

    sub concat {
      my($x,$y) = @_;
    
      return $x if $y eq '';
      return $y if $x eq '';
    
      my($i) = length($x) < length($y) ?  length($x) : length($y);
      while($i > 0) {
          if( substr($x,-$i) eq substr($y,0,$i) )  {
              return $x . substr($y,$i);
          }
          $i--;
      }
      return $x . $y;
    }
    

    It's exactly the same algorithms as yours, I'm just curios if java or perl is faster ;-)

提交回复
热议问题