Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | Java program for the above approach ; Function to count new pairs of strings that can be obtained by swapping first characters of any pair of strings ; Stores the count of pairs ; Generate all possible pairs of strings from the array arr [ ] ; Stores the current pair of strings ; Swap the first characters ; Check if they are already present in the array or not ; If both the strings are not present ; Increment the ans by 1 ; Print the resultant count ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void countStringPairs ( String a [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { char p [ ] = a [ i ] . toCharArray ( ) ; char q [ ] = a [ j ] . toCharArray ( ) ; if ( p [ 0 ] != q [ 0 ] ) { char temp = p [ 0 ] ; p [ 0 ] = q [ 0 ] ; q [ 0 ] = temp ; int flag1 = 0 ; int flag2 = 0 ; for ( int k = 0 ; k < n ; k ++ ) { if ( a [ k ] . equals ( new String ( p ) ) ) { flag1 = 1 ; } if ( a [ k ] . equals ( new String ( q ) ) ) { flag2 = 1 ; } } if ( flag1 == 0 && flag2 == 0 ) { ans = ans + 1 ; } } } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " good " , " bad " , " food " } ; int N = arr . length ; countStringPairs ( arr , N ) ; } }