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 newly created pairs by swapping the first characters of any pairs of strings ; Stores the count all possible pair of strings ; Push all the strings into the Unordered Map ; Generate all possible pairs of strings from the array arr [ ] ; Store the current pair of strings ; Swap the first character ; Check if both string are not present in map ; Print the result ; Driver code
import java . lang . * ; import java . util . * ; class GFG { static void countStringPairs ( String a [ ] , int n ) { int ans = 0 ; Map < String , Integer > s = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { s . put ( a [ i ] , s . getOrDefault ( a [ i ] , 0 ) ) ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { StringBuilder p = new StringBuilder ( a [ i ] ) ; StringBuilder q = new StringBuilder ( a [ j ] ) ; if ( p . charAt ( 0 ) != q . charAt ( 0 ) ) { char t = p . charAt ( 0 ) ; p . setCharAt ( 0 , q . charAt ( 0 ) ) ; q . setCharAt ( 0 , t ) ; if ( ! s . containsKey ( p . toString ( ) ) && ! s . containsKey ( q . toString ( ) ) ) { ans ++ ; } } } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " good " , " bad " , " food " } ; int N = arr . length ; countStringPairs ( arr , N ) ; } }