Java solution for Isomorphic Strings


This is the Java implementation of the problem (Isomorphic Strings) describe in Perl Weekly Challenge. Two strings are isomorphic if one-to-one mapping is possible for every character of the first string to every character of the second string. For example, consider the two strings: “ACAB” and “XCXY”. We can map the characters of the first string to the characters of the second string as follows:

  • ‘A’ maps to ‘X’.
  • ‘C’ maps to ‘C’.
  • ‘B’ maps to ‘Y’.

Hence, the two strings are isomorphic. Now, consider the strings “AAB” and “XYZ”. These are not isomorphic since ‘A’ cannot have a mapping to both ‘X’ and ‘Y’.

Another way to look at it is that two strings are isomorphic if each character in the first string can be replaced by a character to get the second string, and vice-versa.


In this section we will see the working Java implementation of the problem:

import java.util.*;

public class IsomorphicStrings {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(;
        System.out.println("Enter first string");
        String str1 =;
        System.out.println("Enter second string");
        String str2 =;
        System.out.println("Output: " + areStringIsomorphic(str1, str2));

    public static int areStringIsomorphic(String str1, String str2) {
        Set<Character> set1 = convertToSet(str1);
        Set<Character> set2 = convertToSet(str2);
        if (set1.size() != set2.size()) {
            return 0;
        Map<Character, Character> map = new HashMap();
        Iterator<Character> itr1 = set1.iterator();
        Iterator<Character> itr2 = set2.iterator();
        while (itr1.hasNext()) {
            final Character character =;
            if (map.containsKey(character)) {
                if (!map.get(character).equals( {
                   return 0;
            } else {
        return 1;

    private static Set<Character> convertToSet(String str) {
        Set<Character> set = new LinkedHashSet(str.length());
        for (int i = 0; i < str.length(); i++) {
        return set;


Below is the sample output:

Enter first string
Enter second string
Output: 0

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: