0

Given a string s of length n, find the longest string t that occurs both forwards and backwards in s. e.g, s = yabcxqcbaz, then return t = abc or t = cba

I am considering using the generalized suffix tree but I think it would take me O(n^2) time.

i = 0 # Initialize the position on the S
j = 0 # Initialize the position on the Sr
n = len(S) # n is the length of the string
maxLengthPos = (0, 0) # Record the maximum length of such substring found so far and its position

# Iterate through every 
for i in range(n):
    for j in range(n):
        maxL, pos = maxLengthPos
        l = LCE(i, j) # The longest common extension which take O(1) time
        if l > maxL:
            maxLength = (l, i)

Can I implement it in O(n) time?

xxx222
  • 2,980
  • 5
  • 34
  • 53
  • You definitely want to use a suffix tree? You can use dynamic programming and it can be done in O(n) time. – erip Nov 29 '15 at 00:20

1 Answers1

1

You are looking for the longest common substring of s and its reverse. This can indeed be solved using the generalized suffix array or suffix tree of s and reverse(s), in linear time.

There's a conceptionally simpler approach using the suffix automaton of s though. A suffix automaton is a finite automaton that matches exactly the suffixes of a string, and it can be built in linear time. You can find an implementation in C++ in my Github repository. Now you just feed the second string (in this case reverse(s)) into the automaton and record the longest match, which corresponds to the LCS of the two strings.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
  • @BrentWashburne It's non-trivial 60 lines of code, so I don't think I can present it concisely. I will try to give a high-level overview though. – Niklas B. Nov 04 '15 at 11:29
  • While you answered the question (yes, it's possible in linear time), an excellent answer would include a discussion of the algorithm and not just a link. I've seen answers that are much longer than 60 lines, so don't let that be a limitation. – Brent Washburne Nov 04 '15 at 17:19