-1

Given string P with length n, and a function A on P [n] --> [n] that does the following: For every 1 <= k <= n A on P [k] = { the maximum index i such that P[1...i] = P[k...k+i-1] Write an algorithm that's optimal as possible that given string P calculates the value of A on P [k] for every 1<= k <= n

1 Answers1

0

There exist an O(n2) solution for the given problem. Let prefixlen be an n×n array and result be stored in an array res of length n. res[k]=0 implies that there is no longest prefix that matches the substring p[k]..p[k+i-1]. Here p is taken as zero indexed.

for k from 0 to n-1 
  res[k]=0  
 for i from 0 to min(k-1,n-1-k)
   if i==0 then
      if p[0]==p[k]
        arr[k][0]=1
      else 
        arr[k][0]=0
   else if arr[k][i-1]!=0 then
      if p[arr[k][i-1]==p[k+i] then
        arr[k][i]=arr[k][i-1]+1
      else arr[k][i]=arr[k][i-1]
       end if 
   else 
      if p[k]==p[0]  then
         arr[k][i]=1
      else arr[k][i]=0
  res[k]=max(res[k],arr[k][i])
  end for 
 end for
Dante
  • 29
  • 5