Sort string suffix starting positions, then examine only adjacent entries:
def longestRepeated(): (Int, Int, Int) = {
require(N >= 2)
val suffixes = (0 until N).toArray.sortWith(before)
var besti = suffixes(0)
var bestj = suffixes(1)
var bestk = 0
var t = 1
while (t < N) {
val i = suffixes(t - 1)
val j = suffixes(t)
val k = longestFrom(i, j)
if (k > bestk) {
besti = i; bestj = j; bestk = k
}
t += 1
}
(besti, bestj, bestk)
}The while loop retains a best triple among adjacent pairs already visited. All string suffix starting positions are distinct, and the adjacent-suffix characterization proves that considering these pairs suffices. The two definitions named
longestRepeated in parts b and e are alternatives, not duplicate members of one software class.Assuming a comparison sort using comparator calls, sorting takes time, because each comparison scans characters. The final pass takes . Thus overall time is , at worst , with auxiliary storage for indices and ordinary sorting workspace. Merely storing indices does not make string suffix comparisons constant-time; claiming here would omit their cost. Faster suffix-array constructions require additional machinery beyond this comparator-based solution.
Articles by others on the same topic
There are currently no matching articles.