human
Print the longest prefix of the given string which is also the suffix of the same string | Returns length of the longest prefix which is also suffix and the two do not overlap . This function mainly is copy of computeLPSArray ( ) in KMP Algorithm.
Length of the previous longest prefix suffix.
Loop to calculate lps [ i ] for i = 1 to n - 1.
This is tricky . Consider the example . AAACAAAA and i = 7. The idea is similar to search step ..
If len = 0.
Since we are looking for non overlapping parts.
Function that returns the prefix.
Get the length of the longest prefix.
Stores the prefix.
Traverse and add characters.
Returns the prefix.
Driver code"
Solution in Python:
 ... Write me a code to print the longest prefix of the given string which is also the suffix of the same string and the other steps required?
assistant
#Here is code to print the longest prefix of the given string which is also the suffix of the same string and the other steps required.
 def LengthlongestPrefixSuffix ( s ) :
	n = len ( s )
	lps = [ 0 for i in range ( n ) ]
	len1 = 0
	i = 1
	while ( i < n ) :
		if ( s [ i ] == s [ len1 ] ) :
			len1 += 1
			lps [ i ] = len1
			i += 1
		else :
			if ( len1 != 0 ) :
				len1 = lps [ len1 - 1 ]
			else :
				lps [ i ] = 0
				i += 1
	res = lps [ n - 1 ]
	if ( res > int ( n / 2 ) ) :
		return int ( n / 2 )
	else :
		return res
def longestPrefixSuffix ( s ) :
	len1 = LengthlongestPrefixSuffix ( s )
	prefix = " "
	for i in range ( len1 ) :
		prefix += s [ i ]
	return prefix
if __name__ == ' _ _ main _ _ ' :
	s = " abcab "
	ans = longestPrefixSuffix ( s )
	if ( ans == " " ) :
		print ( " - 1" )
	else :
		print ( ans )