I searched online for a C++ Longest Common Substring implementation but failed to find a decent one. I need a LCS algorithm that returns the substring itself, so it's not just LCS.
I was wondering, though, about how I can do this between multiple strings.
My idea was to check the longest one between 2 strings, and then go check all the others, but this is a very slow process which requires managing many long strings on the memory, making my program quite slow.
Any idea of how this can be speeded up for multiple strings? Thank you.
Important Edit One of the variables I'm given determines the number of strings the longest common substring needs to be in, so I can be given 10 strings, and find the LCS of them all (K=10), or LCS of 4 of them, but I'm not told which 4, I have to find the best 4.
Here is an excellent article on finding all common substrings efficiently, with examples in C. This may be overkill if you need just the longest, but it may be easier to understand than the general articles about suffix trees.
Here is a C# version to find the Longest Common Substring using dynamic programming of two arrays (you may refer to: http://codingworkout.blogspot.com/2014/07/longest-common-substring.html for more details)
Where unit tests are:
There is a very elegant Dynamic Programming solution to this.
Let
LCSuff[i][j]
be the longest common suffix betweenX[1..m]
andY[1..n]
. We have two cases here:X[i] == Y[j]
, that means we can extend the longest common suffix betweenX[i-1]
andY[j-1]
. ThusLCSuff[i][j] = LCSuff[i-1][j-1] + 1
in this case.X[i] != Y[j]
, since the last characters themselves are different,X[1..i]
andY[1..j]
can't have a common suffix. Hence,LCSuff[i][j] = 0
in this case.We now need to check maximal of these longest common suffixes.
So,
LCSubstr(X,Y) = max(LCSuff(i,j))
, where1<=i<=m
and1<=j<=n
The algorithm pretty much writes itself now.
The answer is GENERALISED SUFFIX TREE. http://en.wikipedia.org/wiki/Generalised_suffix_tree
You can build a generalised suffix tree with multiple string.
Look at this http://en.wikipedia.org/wiki/Longest_common_substring_problem
The Suffix tree can be built in O(n) time for each string, k*O(n) in total. K is total number of strings.
So it's very quick to solve this problem.
I tried several different solutions for this but they all seemed really slow so I came up with the below, didn't really test much, but it seems to work a bit faster for me.
Find the largest substring from all strings under consideration. From N strings, you'll have N substrings. Choose the largest of those N.