Javatpoint Logo
Javatpoint Logo

Isomorphic String in Java

It is a very interesting problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, Uber, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to discuss what is isomorphic string and how to check if the string is isomorphic or not with different approaches and logic. Also, we will create Java programs for the same.

Isomorphic String

The string is called isomorphic if the letters of the one string can be mapped to get the second string. Mapping means replacing all occurrences of a letter with another letter but the ordering of the letters remains unchanged. Note that no two letters may map to the same letter but a letter may map to itself.

Let's understand it through examples.

Example 1:

Suppose, string1 is ABACB and string2 is XPZ. Now map string1 to string2.

Character Mapping
A X
B P
C Z

Replace A -> X, B -> P, A -> X, C -> Z, B -> P.

Hence, we observe that string1 and string2 are isomorphic to each other.

Let's see another example.

Example 2:

Suppose, string1 is PQPRQP and string2 is XPZW. Now map string1 to string2.

Character Mapping
P T
Q U
R V
P W

Replace P -> T, Q -> U, P -> T, R -> V, Q -> U, P -> W.

Hence, we observe that string1 and string2 are not isomorphic to each other.

Algorithm

  1. Consider a mapping table which maps each character from the first string to one and only character in the second string.
  2. Consider another table say mappedBefore table. It records each character from the second string which is already related to a character from the second string.
  3. Read the first-string character by character.
  4. If the character is presented in the mapping table, gets its mapping.
  5. Read the corresponding character from the second string.
  6. Check if the mapping and the read character from the second string are not the same, return false.
  7. Else, check if the read character from the first string does not exist in the mapping table and do the following:
    1. Read the corresponding character from the second string.
    2. If the character exists in the mappedBefore table then return false.
    3. Else, add the read character from the first and the second table to the mapping table.
  8. Move to step 3 and continue.
  9. Return true.

Let's implement the above algorithm in a Java program.

Java Program to Check if the Two Strings are Isomorphic or not

IsomorphicString.java

Output:

Are KITE and ZXBN Isomorphic? true

Next TopicJava ImageIO Class





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA