in reply to An efficient way to gather a common portion of several strings' beginnings
This is O(n) rather than the O(n2) of your solution:
#! perl -slw use strict; my @strings = ( 'string that I need to gather the common base from: number 1 and some +other junk in it', 'string that I need to gather the common base from: number 2 and some +other junk in it', 'string that I need to gather the common base number 4 and some other +junk in it', 'string that I need to gather the common base from: number 3 and some +other junk in it', ); my( $mask ) = ( $strings[ 0 ] ^ $strings[ 1 ] ) =~ m[(^\0+)]; my $common = substr $strings[ 0 ], 0, length $mask; for my $i ( 2 .. $#strings ) { if( substr( $strings[ $i ], 0, length $common ) ne $common ) { ( $mask ) = ( $strings[ 0 ] ^ $strings[ $i ] ) =~ m[(^\0+)]; $common = substr $strings[ 0 ], 0, length $mask; } } print "'$common'"; __END__ C:\test>1147616 'string that I need to gather the common base '
|
|---|