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?
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With