I’m trying to implement something that finds the common suffix between a number of strings, for the sake of illustrations, consider the following:
"The quick brown fox" "The not so quick brown fox" "The smelly brown fox" "The vicious brown fox"
To a human, it’s hopefully obvious that the common suffix here is " brown fox", and my naive implementation currently takes the first pair of strings, converts them both to char arrays, and then iterates over these until a character is found to be different, I then create a new string from this, and crop it to the length, reverse it back to the correct order, and return that. I then repeat using the result from the first string with the next string in the list.
Whilst this is loosely O(N), performance of this isn’t as good as I’d like, and I wondered before I spend a long time buried in the profiler if I’d missed a quicker way to do this within the .NET framework?
EDIT:
Taking out the double reverses (which then means we don’t need to convert to char arrays) gives pretty good performance, for the record, my implementation looks a little like:
private string GetCommonSuffix(string[] lines)
{
int lineCount = lines.GetLength(0);
string currentSuffix = lines[0];
int currentSuffixLength = currentSuffix.Length;
for (int i = 1; i < lineCount; i++)
{
string thisLine = lines[i];
if (!thisLine.EndsWith(currentSuffix))
{
int thisLineLength = thisLine.Length;
int maxPossible = thisLineLength < currentSuffixLength ? thisLineLength : currentSuffixLength;
if (maxPossible == 0)
{
return string.Empty;
}
for (int j = 1; j < maxPossible; j++)
{
if( currentSuffix[ currentSuffixLength - j ] != thisLine[ thisLineLength - j ] )
{
currentSuffix = currentSuffix.Substring(currentSuffixLength - j + 1, j - 1);
currentSuffixLength = j - 1;
break;
}
}
}
}
return currentSuffix;
}
Well, to start with you don’t need to convert the strings into char arrays. You can use indexers into the strings to fetch individual characters.
It’s probably worth thinking of it as a number rather than a string… each pairwise comparison will give you a maximal value, and the final number (the size of the suffix) is the minimum of those maxima.
So two approaches suggest themselves:
Personally I’d probably go with the first approach though – it won’t have as good cache coherency, but I think it’ll be better in some situations (e.g. many strings, all but one of which have a long common suffix.
(Of course, once you’ve got the length, getting the actual substring is very simple.)