How to find the longest common prefix of two strings in Scala?
I probably can code an "imperative" solution (with an index i
running over the strings while s(i) == t(i)
) but I am looking for a "functional-style" solution (without updating the index variable explicitly, for instance).
Another recursive version.
It's over 10 times quicker than sjj's and over twice as fast as missingfaktor's. Java's
substring
is fast becauseString
is immutable.If speed is the deal, go imperative.
EDIT:
As per Luigi's suggestion:
To get the common prefix of any number of strings:
Recursive version:
The imperative version can be simplified to