You can first compare two of the strings, get the longest common string, and then take the result and compare it to the third string. And keeping do it until the last string in the list will give you the longest common string for all the strings. This can be achieved using Fold
, for example:
ls = {"home/dir1/dir2/jmoasd.txt", "home/dir1/dir2/ivbnoxcihv.txt",
"home/dir1/dir2/siuhgiuchv.txt"};
Fold[LongestCommonSubsequence, First@ls, Rest@ls]
(* "home/dir1/dir2/" *)
Edit
As JasonB pointed out, this method may fail when the sequence is not line up from the beginning in each string. In that case, one can use the method by Dr. belisarius:
longest[ls_] :=
FromCharacterCode[(ToCharacterCode /@
ls) /. {{___, Longest[y__], ___}, {___, y__, ___} ...} -> {y}]
ls // longest
(* "home/dir1/dir2/" *)
It also works for cases like:
{"aaaxxbbb", "bbbxxccc", "cccxxaaa"} // longest
(* "xx" *)
"AABB"
and"BBAA"
, both"AA"
and"BB"
are longest common substrings. This also explains why in case of $>2$ strings you cannot just fold over the list of strings, finding LCS between only 2 strings at each step. $\endgroup$