How To Check If Two Strings Are Isomorphic In Java

Introduction

Hi friends, In this blog we will learn about how to check two given string is isomorphic or not. In the context of strings, "isomorphic" refers to a specific type of relationship between two strings where they have a one-to-one mapping of characters from one string to another.

In simpler terms, two strings are considered isomorphic if you can replace all occurrences of characters in the first string with corresponding characters in the second string while preserving the order of characters, resulting in identical strings.

How to check if two strings are isomorphic

import java.util.*;

public class IsomorphicString {
    public static boolean areIsomorphic(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }

        Map<Character, Character> map = new HashMap<>();
        Map<Character, Boolean> mapped = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char charS = s.charAt(i);
            char charT = t.charAt(i);

            if (map.containsKey(charS)) {
                if (map.get(charS) != charT) {
                    return false;
                }
            } else {
                if (mapped.containsKey(charT)) {
                    return false;
                }
                map.put(charS, charT);
                mapped.put(charT, true);
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String s1 = "egg";
        String t1 = "add";
        System.out.println("Are 'egg' and 'add' isomorphic? " + areIsomorphic(s1, t1));

        String s2 = "foo";
        String t2 = "bar";
        System.out.println("Are 'foo' and 'bar' isomorphic? " + areIsomorphic(s2, t2));
    }
}

Explanation

Here we are using two HashMaps to store the mapping of characters from string s to string t, and mapped to keep track of characters in string t that have already been mapped.

let's consider two strings, egg and add. In this case, e can be replaced by a, g can be replaced by d, and g can again be replaced by d. Therefore, these strings are isomorphic.

However, strings like foo and bar are not isomorphic because there is no way to map characters from one string to the other in a way that maintains the order and results in identical strings.

Output

Check If Two Strings Are Isomorphic in Java 

Conclusion

In this blog, we have seen how we can check whether two strings are isomorphic or not in java. Thanks for reading and hope you like it. If you have any suggestions or queries on this blog, please share your thoughts. You can read my other articles by clicking here.

Happy learning, friends!