Largest substring of str2 which is a prefix of str1 | Python3 implementation of the approach ; Function to return the largest substring in str2 which is a prefix of str1 ; To store the index in str2 which matches the prefix in str1 ; While there are characters left in str1 ; If the prefix is not found in str2 ; Remove the last character ; Prefix found ; No substring found in str2 that matches the prefix of str1 ; Driver code
import operator NEW_LINE def findPrefix ( str1 , str2 ) : NEW_LINE INDENT pos = False ; NEW_LINE while ( len ( str1 ) != 0 ) : NEW_LINE INDENT if operator . contains ( str2 , str1 ) != True : NEW_LINE INDENT str1 = str1 [ 0 : len ( str1 ) - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT pos = operator . contains ( str2 , str1 ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( pos == False ) : NEW_LINE INDENT return " - 1" ; NEW_LINE DEDENT return str1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksfor " ; NEW_LINE str2 = " forgeeks " ; NEW_LINE print ( findPrefix ( str1 , str2 ) ) ; NEW_LINE DEDENT