Longest common prefix: Difference between revisions

Line 124:
 
The above runs without output.
 
 
An alternative solution that takes advantage of the observation that the longest common prefix of a set of strings must be the same as the longest common prefix of the lexicographically minimal string and the lexicographically maximal string, since moving away lexicographically can only shorten the common prefix, never lengthening it. Finding the min and max could do a lot of unnecessary work though, if the strings are long and the common prefix is short.
<lang python>from itertools import takewhile
 
def lcp(*s):
return ''.join(a for a,b in takewhile(lambda (a,b): a == b,
zip(min(s), max(s))))</lang>
 
=={{header|Scala}}==
Anonymous user