Created
August 9, 2012 23:50
-
-
Save boopsie/3309172 to your computer and use it in GitHub Desktop.
Perl Longest Common Prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# returns longest common prefix of a list of strings | |
sub lcp | |
{ | |
my $match = shift; | |
substr($match, (($match ^ $_) =~ /^\0*/, $+[0])) = '' for @_; | |
$match; | |
} |
Is there a version to return the longest common suffix of a list of strings?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two things:
Thanks!
My own analysis, for anyone who is curious ---
($match ^ $_) =~ /^\0*/
matches the run of prefix characters in common between$match
and$_
(string XOR produces null ==\0
where characters match).$+[0]
is the offset of the end of that run.substr() = ''
removes the part of$match
starting at the leftmost char position that differs between$match
and$_
.for @_
loops over all strings except the first (which was handled by the initialshift
), removing the mismatched suffix each time.