
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Longest Substring which is Prefix, Suffix and Present Inside String in Python
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
-
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 −
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 (iInput
"languagepythonlanguageinterestinglanguage"Output
language