Longest Common Substring in an Array of Strings | function to find the stem ( longestcommon substring ) from the string array ; Determine size of the array ; Take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; Check if the generated stem is common to all words ; If current substring is present in all strings and its length is greater than current result ; Driver Code ; Function call
def findstem ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE s = arr [ 0 ] NEW_LINE l = len ( s ) NEW_LINE res = " " NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( i + 1 , l + 1 ) : NEW_LINE INDENT stem = s [ i : j ] NEW_LINE k = 1 NEW_LINE for k in range ( 1 , n ) : NEW_LINE INDENT if stem not in arr [ k ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( k + 1 == n and len ( res ) < len ( stem ) ) : NEW_LINE INDENT res = stem NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " grace " , " graceful " , " disgraceful " , " gracefully " ] NEW_LINE stems = findstem ( arr ) NEW_LINE print ( stems ) NEW_LINE DEDENT