Check if two given strings are isomorphic to each other | Java 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 . 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
import java . io . * ; import java . util . * ; class Isomorphic { static int size = 256 ; static boolean areIsomorphic ( String str1 , String str2 ) { int m = str1 . length ( ) ; int n = str2 . length ( ) ; if ( m != n ) return false ; Boolean [ ] marked = new Boolean [ size ] ; Arrays . fill ( marked , Boolean . FALSE ) ; int [ ] map = new int [ size ] ; Arrays . fill ( map , - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( map [ str1 . charAt ( i ) ] == - 1 ) { if ( marked [ str2 . charAt ( i ) ] == true ) return false ; marked [ str2 . charAt ( i ) ] = true ; map [ str1 . charAt ( i ) ] = str2 . charAt ( i ) ; } else if ( map [ str1 . charAt ( i ) ] != str2 . charAt ( i ) ) return false ; } return true ; } public static void main ( String [ ] args ) { boolean res = areIsomorphic ( " aab " , " xxy " ) ; System . out . println ( res ) ; res = areIsomorphic ( " aab " , " xyz " ) ; System . out . println ( res ) ; } }