Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the longest repeating string and the number of times it repeats in a given string

Tags:

c

algorithm

For example, given string "abc fghi bc kl abcd lkm abcdefg", the function should return string "abcd" and the count of 2.

A O(n^2) solution seems easy but I am looking for a better solution.

Edited: If nothing better than O(n^2) is possible than which approach would be best performance wise.

like image 699
AJ. Avatar asked Dec 23 '22 06:12

AJ.


2 Answers

You can solve this in linear time by building a suffix tree and taking a path from the root to the deepest internal node; this will give you the longest repeated string. Once you have that string, it's trivial to count the number of times it appears.

like image 73
jason Avatar answered Jan 26 '23 01:01

jason


A state machine could probably give something better than big-O(N^2).

EDIT: The suffix tree suggested in the other answer is such an implementation of a state machine :)

like image 43
Mahmoud Al-Qudsi Avatar answered Jan 26 '23 01:01

Mahmoud Al-Qudsi