Lexical sort is n*log(n)*m (character comparisons) vs n*m of the basic loop. It is certainly not optimal for arbitrary inputs.
Update. Some benchmarking shows either of the two following versions ought to perform adequately, in practice. I'll leave it to the reader's discretion...
# however, these assume strings don't contain \0 sub lcp_v4 { my ($e, $s) = ("", @_); $e |= $_ ^ $s for @_; $e =~ m/^\0*/; substr($s, 0, $+[0]); } sub lcp_v5 { my ($a, $b) = (sort @_)[0,-1]; ($a ^ $b) =~ m/^\0*/; substr($a, 0, $+[0]); } use List::Util qw(minstr maxstr); sub lcp_v6 { my ($a, $b) = (&minstr, &maxstr); ($a ^ $b) =~ m/^\0*/; substr($a, 0, $+[0]); }
Update 2. Sometimes one is the most oblivious to the most obvious. Added the third version lcp_v6.
In reply to Re^2: An efficient way to gather a common portion of several strings' beginnings
by oiskuu
in thread An efficient way to gather a common portion of several strings' beginnings
by igoryonya
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |