Maximize product of lengths of strings having no common characters | Java program for the above approach ; Function to count the number of set bits in the integer n ; Stores the count of set bits in n ; Return the count ; Function to find the maximum product of pair of strings having no common characters ; Stores the integer equivalent of the strings ; Traverse the array of strings ; Traverse the current string ; Store the current bit position in bits [ i ] ; Store the required result ; Traverse the array , bits [ ] to get all unique pairs ( i , j ) ; Check whether the strings have no common characters ; Update the overall maximum product ; Print the maximum product ; Driver Code
import java . io . * ; class GFG { public static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } public static void maximumProduct ( String [ ] words ) { int [ ] bits = new int [ words . length ] ; for ( int i = 0 ; i < words . length ; i ++ ) { for ( int j = 0 ; j < words [ i ] . length ( ) ; j ++ ) { bits [ i ] = bits [ i ] | 1 << ( words [ i ] . charAt ( j ) - ' a ' ) ; } } int result = 0 ; for ( int i = 0 ; i < bits . length ; i ++ ) { for ( int j = i + 1 ; j < bits . length ; j ++ ) { if ( ( bits [ i ] & bits [ j ] ) == 0 ) { int L = countSetBits ( bits [ i ] ) ; int R = countSetBits ( bits [ j ] ) ; result = Math . max ( L * R , result ) ; } } } System . out . println ( result ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " abcw " , " baz " , " foo " , " bar " , " xtfn " , " abcdef " } ; maximumProduct ( arr ) ; } }