Java solution for Isomorphic Strings

Overview

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.

Code

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.in);
        System.out.println("Enter first string");
        String str1 = scanner.next();
        System.out.println("Enter second string");
        String str2 = scanner.next();
        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 = itr1.next();
            if (map.containsKey(character)) {
                if (!map.get(character).equals(itr2.next())) {
                   return 0;
                }
            } else {
                map.put(character, itr2.next());
            }
        }
        return 1;
    }

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

Output

Below is the sample output:

Enter first string
sum
Enter second string
add
Output: 0

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: