×

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or not. It is one of the popular interview questions for top-rated IT companies like Amazon, Accenture, Google, etc. This problem enhances the thinking power and problem-solving ability of students. The intention is to check the thinking – critical, and logical of the student.

Isomorphic String

The string is referred to as isomorphic if the letters of one string can be mapped to obtain the second string. By Mapping, we mean replacing all existences of a letter with another letter without changing the order of the letters.It should benoted that no two letters may map to the identical letter but a letter may map to itself.

Now, let us try to grasp it through an example.

Let us consider, string1 as DEDFE and string2 as WVZ. Now try to map string1 to string2.

CharacterMapping
DW
EV
FZ

Replace the letters of the string

D ->W, E ->V, D ->W, F -> Z, E ->V.

Recalling the definition of isomorphic, we observe that string1 and string2 are isomorphic to one another.

Example 2:

Let us consider, string1 is EFEFGE and string2 is WVZU. Now try to map string1 to string2.

CharacterMapping
EW
FV
GZ
EU

Replacing the letters,

E ->W, F ->V, E ->W, F -> V, G ->Z, E ->U.

Recalling the definition, we can say that string1 and string2 are not isomorphic to one another.

Example 3:

Let us consider, string1 as SERVICE and string2 asTUVWXYZ. Now try to map string1 to string2.

CharacterMapping
ST
EU
RV
VW
IX
CY
EZ

Replacing the letters,

S ->T, E ->U, R ->V, I ->X, C ->Y, E ->Z.

Recalling the definition, we can say that string1 and string2 are not isomorphic to one another. Two Es in string 1 is mapped with two different letters in string 2.

Set of Rules

  1. A mapping table is to be taken into accountthat would map every character from the first string to the only character in the second string.
  2. Another table is considered; call it mapped before the table to record every character from the second string which is already connected to a character from the second string.
  3. The first stringis read character by character.
  4. Get the mapping if the character gets presented in the mapping table.
  5. The equivalent character from the second string is read.
  6. Return false if the mapping and the studied character from the 2nd string are different.
  7. Otherwise, check if the studied character from the first string does not exist in the mapping table and take the following action:
    1. Read the equivalent character from the subsequent string.
    1. Return false if the character resides in the table named mappedBefore.
    1. Otherwise, include the read character from the first table and the read character from the second table in the mapping table.
  8. Go to step no. 3 and continue.
  9. Return true.

Implementation:

Now, let us see a java program to understand the explained concept.

import java.util.*;  
// creation of the class named IsomorphicString
public class IsomorphicString
{    


public static void main(String args[])   
{  
//strings to check whether they are isomorphic in nature or not    


String strg1 = "SERVICE", strg2 = "TUVWXYZ";  


System.out.println("Are "+strg1 +" and "+strg2 +" Isomorphic? "+isIsomorphicString(strg1, strg2));  


}  
//function to check if the given string is isomorphic or not  


public static booleanisIsomorphicString(String strg1, String strg2)   
{  


if (strg1 == null || strg2 == null || strg1.length() != strg2.length())  


//it returns false if string1 and string2 are null and of varying lengths
return false;  


//creation of an instance of Map  
Map<Character, Character> map = new HashMap<>();  
for (int j = 0; j < strg1.length(); j++)   
{  
//finding the character of the string at i-th position  
char char_strg1 = strg1.charAt(j), char_strg2 = strg2.charAt(j);  
//checks whether a particular key (i-th character) is being mapped into the Map or not  


if (map.containsKey(char_strg1))   
{  
if (map.get(char_strg1) != char_strg2)  
//returns false if the character of the first string and the character of the second string are not equal
return false;  
}  
else   
{  
//checking if the specific keyi.e (i-th character) is being mapped into the Map or not      
if (map.containsValue(char_strg2))            
return false;  
//adding key and value to the map  
.put(char_strg1, char_strg2);  
}  
}  
return true;  
}  
}  

Output:

Isomorphic String in Java

Explanation: The given two strings are not isomorphic as it violates the definition of an isomorphic string. There are two E in string 1 mapped to different letters in string 2.


Related Topics

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.