Longest Common Prefix using Word by Word Matching | A Utility Function to find the common prefix between strings - str1 and str2 ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; Driver Code
def commonPrefixUtil ( str1 , str2 ) : NEW_LINE INDENT result = " " ; NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while i <= n1 - 1 and j <= n2 - 1 : NEW_LINE INDENT if ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT result += str1 [ i ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return ( result ) NEW_LINE DEDENT def commonPrefix ( arr , n ) : NEW_LINE INDENT prefix = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix = commonPrefixUtil ( prefix , arr [ i ] ) NEW_LINE DEDENT return ( prefix ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE n = len ( arr ) NEW_LINE ans = commonPrefix ( arr , n ) NEW_LINE if ( len ( ans ) ) : NEW_LINE INDENT print ( " The ▁ longest ▁ common ▁ prefix ▁ is ▁ - " , ans ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There ▁ is ▁ no ▁ common ▁ prefix " ) NEW_LINE DEDENT DEDENT