Check if two given strings are isomorphic to each other | Javascript program to check if two strings are isomorphic ; 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 and 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 code
let size = 256 ; function areIsomorphic ( str1 , str2 ) { let m = str1 . length ; let n = str2 . length ; if ( m != n ) return false ; let marked = new Array ( size ) ; for ( let i = 0 ; i < size ; i ++ ) marked [ i ] = false ; let map = new Array ( size ) ; map . fill ( 0 ) ; for ( let i = 0 ; i < size ; i ++ ) map [ i ] = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( map [ str1 [ i ] . charCodeAt ( ) ] == - 1 ) { if ( marked [ str2 [ i ] . charCodeAt ( ) ] == true ) return false ; marked [ str2 [ i ] . charCodeAt ( ) ] = true ; map [ str1 [ i ] . charCodeAt ( ) ] = str2 [ i ] . charCodeAt ( ) ; } else if ( map [ str1 [ i ] . charCodeAt ( ) ] != str2 [ i ] . charCodeAt ( ) ) return 0 ; } return 1 ; } let res = areIsomorphic ( " " , " " ) ; document . write ( res + " " ) ; res = areIsomorphic ( " " , " " ) ; document . write ( res ) ;