Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countStringPairs ( string a [ ] , int n ) { int ans = 0 ; unordered_map < string , int > s ; for ( int i = 0 ; i < n ; i ++ ) { s [ a [ i ] ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { string p = a [ i ] ; string q = a [ j ] ; if ( p [ 0 ] != q [ 0 ] ) { swap ( p [ 0 ] , q [ 0 ] ) ; if ( s . find ( p ) == s . end ( ) && s . find ( q ) == s . end ( ) ) { ans ++ ; } } } } cout << ans ; } int main ( ) { string arr [ ] = { " good " , " bad " , " food " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countStringPairs ( arr , N ) ; return 0 ; }