Reputation: 119
Are there any ways to use linear-time algorithm to find the longest prefix of a string s that is a substring of the reversal of the string s?
Upvotes: 4
Views: 2078
Reputation: 6021
Yes, there's an O(n)
solution with a suffix tree. Suppose n
is the length of string s
.
s
rev
, the reversal of string s
, is O(n)
(and actually it can be O(1)
, but it doesn't matter here).s
rev
can be built in O(n)
time.s
in s
rev
can be found in O(n)
time using the suffix tree.Upvotes: 4
Reputation: 3865
Apply Knuth-Morris-Pratt algorithm to search for the given string (S) in the reversed string (T). At each iteration it will find the longest prefix of S that is a suffix of T[1..i]. Then you just need to find the maximum of the lengths of these prefixes.
Upvotes: 4