Program to find Greatest Common Divisor ( GCD ) of N strings | Java program for the above approach ; Function that finds gcd of 2 strings ; If str1 length is less than that of str2 then recur with gcd ( str2 , str1 ) ; If str1 is not the concatenation of str2 ; GCD string is found ; Cut off the common prefix part of str1 & then recur ; Function to find GCD of array of strings ; Return the GCD of strings ; Driver Code ; Given array of strings ; Function Call
class GCD { static String gcd ( String str1 , String str2 ) { if ( str1 . length ( ) < str2 . length ( ) ) { return gcd ( str2 , str1 ) ; } else if ( ! str1 . startsWith ( str2 ) ) { return " " ; } else if ( str2 . isEmpty ( ) ) { return str1 ; } else { return gcd ( str1 . substring ( str2 . length ( ) ) , str2 ) ; } } static String findGCD ( String arr [ ] , int n ) { String result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { result = gcd ( result , arr [ i ] ) ; } return result ; } public static void main ( String [ ] args ) { String arr [ ] = new String [ ] { " GFGGFG " , " GFGGFG " , " GFGGFGGFGGFG " } ; int n = arr . length ; System . out . println ( findGCD ( arr , n ) ) ; } }