Find the longest sub-string which is prefix, suffix and also present inside the string in Python

PythonServer Side ProgrammingProgramming

Suppose we have a given string, we have to find the largest sub-string which is a prefix, a suffix and a sub-string of that given string. If there is no such substring, then return -1.

So, if the input is like "languagepythonlanguageinterestinglanguage", then the output will be "language"

To solve this, we will follow these steps −

  • Define a function get_lps() . This will take string

  • n := size of string

  • long_pref_suff := an array of size n, and fill with 0

  • size := 0, long_pref_suff[0] := 0, i := 1

  • while i < n is non-zero, do

    • if string[i] is same as string[size], then

      • size := size + 1

      • long_pref_suff[i] := size

      • i := i + 1

    • otherwise,

      • if size is not same as 0, then

        • size := long_pref_suff[size - 1]

      • otherwise,

        • long_pref_suff[i] := 0

        • i := i + 1

  • return long_pref_suff

  • From the main method, do the following −

  • long_pref_suff := get_lps(string)

  • n := size of string

  • if long_pref_suff[n - 1] is same as 0, then

    • return -1

  • for i in range 0 to n - 1, do

    • if long_pref_suff[i] is same as long_pref_suff[n - 1], then

      • return substring of string[from index 0 to long_pref_suff[i]]

  • if long_pref_suff[long_pref_suff[n - 1] - 1] is same as 0, then

    • return -1

  • otherwise,

    • return substring of string[from index 0 to long_pref_suff[long_pref_suff[n - 1] - 1]]

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def get_lps(string):
   n = len(string)
   long_pref_suff = [0 for i in range(n)]
   size = 0
   long_pref_suff[0] = 0
   i = 1
   while (i < n):
      if (string[i] == string[size]):
         size += 1
         long_pref_suff[i] = size
         i += 1
      else:
         if (size != 0):
            size = long_pref_suff[size - 1]
         else:
            long_pref_suff[i] = 0
            i += 1
   return long_pref_suff
def get_longest_substr(string):
   long_pref_suff = get_lps(string)
   n = len(string)
   if (long_pref_suff[n - 1] == 0):
      return -1
   for i in range(0,n - 1):
      if (long_pref_suff[i] == long_pref_suff[n - 1]):
         return string[0:long_pref_suff[i]]
      if (long_pref_suff[long_pref_suff[n - 1] - 1] == 0):
         return -1
      else:
         return string[0:long_pref_suff[long_pref_suff[n - 1] - 1]]

string = "languagepythonlanguageinterestinglanguage"
print(get_longest_substr(string))

Input

"languagepythonlanguageinterestinglanguage"

Output

language
raja
Published on 20-Aug-2020 07:46:41
Advertisements