Write a Java program to check if two given strings are isomorphic or not
Expected Output:
Is abca and zbxz are Isomorphic? true
import java.util.*; public class Solution { public static void main(String[] args) { String str1 = "abca"; String str2 = "zbxz"; System.out.println("Is "+str1 +" and "+str2 +" are Isomorphic? "+is_Isomorphic(str1, str2)); } public static boolean is_Isomorphic(String str1, String str2) { if (str1 == null || str2 == null || str1.length() != str2.length()) return false; Map<Character, Character> map = new HashMap<>(); for (int i = 0; i < str1.length(); i++) { char char_str1 = str1.charAt(i), char_str2 = str2.charAt(i); if (map.containsKey(char_str1)) { if (map.get(char_str1) != char_str2) return false; } else { if (map.containsValue(char_str2)) return false; map.put(char_str1, char_str2); } } return true; } }
Sample Output:
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer