Check if two given strings are isomorphic to each other | C ++ program for the above approach ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one correspondence ; For counting the previous appearances of character in both the strings ; Process all characters one by one ; For string to be isomorphic the previous counts of appearances of current character in both string must be same if it is not same we return false . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHARS  26 NEW_LINE bool areIsomorphic ( string str1 , string str2 ) { int n = str1 . length ( ) , m = str2 . length ( ) ; if ( n != m ) return false ; int count [ MAX_CHARS ] = { 0 } ; int dcount [ MAX_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { count [ str1 [ i ] - ' a ' ] ++ ; dcount [ str2 [ i ] - ' a ' ] ++ ; if ( count [ str1 [ i ] - ' a ' ] != dcount [ str2 [ i ] - ' a ' ] ) return false ; } return true ; } int main ( ) { cout << areIsomorphic ( " aab " , " xxy " ) << endl ; cout << areIsomorphic ( " aab " , " xyz " ) << endl ; return 0 ; }