4

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.

3
  • 4
    Your SO user name is a bit of a give away. Commented Jan 31, 2010 at 14:35
  • 3
    thats intentional to ward off the SNOBS. Commented Jan 31, 2010 at 14:38
  • 1
    Longest repeated substring problem: en.wikipedia.org/wiki/Longest_repeated_substring_problem Commented Jan 31, 2010 at 14:44

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.