Find the longest common starting substring in a set of strings [closed] Find the longest common starting substring in a set of strings [closed] python python

Find the longest common starting substring in a set of strings [closed]


It's a matter of taste, but this is a simple javascript version:It sorts the array, and then looks just at the first and last items.

//longest common starting substring in an array

function sharedStart(array){    var A= array.concat().sort(),     a1= A[0], a2= A[A.length-1], L= a1.length, i= 0;    while(i<L && a1.charAt(i)=== a2.charAt(i)) i++;    return a1.substring(0, i);}

DEMOS

sharedStart(['interspecies', 'interstelar', 'interstate'])  //=> 'inters'sharedStart(['throne', 'throne'])                           //=> 'throne'sharedStart(['throne', 'dungeon'])                          //=> ''sharedStart(['cheese'])                                     //=> 'cheese'sharedStart([])                                             //=> ''sharedStart(['prefix', 'suffix'])                           //=> ''


In Python:

>>> from os.path import commonprefix>>> commonprefix('interspecies interstelar interstate'.split())'inters'


Ruby one-liner:

l=strings.inject{|l,s| l=l.chop while l!=s[0...l.length];l}