Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the longest prefix of a string s that is a substring of the reversal of the string s

Tags:

java

algorithm

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?

like image 783
user605947 Avatar asked Feb 25 '23 01:02

user605947


2 Answers

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.

like image 101
adamax Avatar answered Mar 22 '23 23:03

adamax


Yes, there's an O(n) solution with a suffix tree. Suppose n is the length of string s.

  1. Computing srev, the reversal of string s, is O(n) (and actually it can be O(1), but it doesn't matter here).
  2. A suffix tree for srev can be built in O(n) time.
  3. Longest prefix of s in srev can be found in O(n) time using the suffix tree.
like image 28
rlibby Avatar answered Mar 23 '23 00:03

rlibby