Longest Common Substring in an Array of Strings | Java program to find the stem of given list of words ; function to find the stem ( longest common 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
import java . io . * ; import java . util . * ; class stem { public static String findstem ( String arr [ ] ) { int n = arr . length ; String s = arr [ 0 ] ; int len = s . length ( ) ; String res = " " ; for ( int i = 0 ; i < len ; i ++ ) { for ( int j = i + 1 ; j <= len ; j ++ ) { String stem = s . substring ( i , j ) ; int k = 1 ; for ( k = 1 ; k < n ; k ++ ) if ( ! arr [ k ] . contains ( stem ) ) break ; if ( k == n && res . length ( ) < stem . length ( ) ) res = stem ; } } return res ; } public static void main ( String args [ ] ) { String arr [ ] = { " grace " , " graceful " , " disgraceful " , " gracefully " } ; String stems = findstem ( arr ) ; System . out . println ( stems ) ; } }