Check if two given strings are isomorphic to each other | C ++ program to check if two strings are isomorphic ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one corresponance ; To mark visited characters in str2 ; To store mapping of every character from str1 to that of str2 . Initialize all entries of map as - 1. ; Process all characters one by on ; If current character of str1 is seen first time in it . ; If current character of str2 is already seen , one to one mapping not possible ; Mark current character of str2 as visited ; Store mapping of current characters ; If this is not first appearance of current character in str1 , then check if previous appearance mapped to same character of str2 ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHARS  256 NEW_LINE bool areIsomorphic ( string str1 , string str2 ) { int m = str1 . length ( ) , n = str2 . length ( ) ; if ( m != n ) return false ; bool marked [ MAX_CHARS ] = { false } ; int map [ MAX_CHARS ] ; memset ( map , -1 , sizeof ( map ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( map [ str1 [ i ] ] == -1 ) { if ( marked [ str2 [ i ] ] == true ) return false ; marked [ str2 [ i ] ] = true ; map [ str1 [ i ] ] = str2 [ i ] ; } else if ( map [ str1 [ i ] ] != str2 [ i ] ) return false ; } return true ; } int main ( ) { cout << areIsomorphic ( " aab " , " xxy " ) << endl ; cout << areIsomorphic ( " aab " , " xyz " ) << endl ; return 0 ; }