Perl - longest common prefix of 2 or more strings? -
how can create perl subroutine take in array , find longest common prefix 2 or more of elements? (strings)
i have code:
sub longest_common_prefix { $prefix = shift; (@_) { chop $prefix while (! /^\q$prefix\e/); } return $prefix; }
but works if looking longest common prefix of all strings.
for example, if pass array following strings:
aaabgfb aaajjjj jjfkbbb aaahghg
i want return aaa
answer.
thanks!
one way store information in hash. in example, set hash key length of each prefix, , value being actual prefix found.
note method overwrites key , value if same-length prefix exists, you'll last prefix found of longest length (sort()
takes care of finding longest one).
the regex says "find first character in string , capture it, , use char found in second capture, , capture many there are". string join()
ed scalar , put hash.
use warnings; use strict; %prefixes; while (<data>){ $prefix = join '', /^(.)(\1+)/; $prefixes{length $prefix} = $prefix; } $longest = (sort {$b <=> $a} keys %prefixes)[0]; print "$prefixes{$longest}\n"; __data__ aabgfb aaajjjj jjfkbbb aaahghg
output:
aaa
Comments
Post a Comment