# Python - Check if two strings are isomorphic in nature

PythonServer Side ProgrammingProgramming

When it is required to check if two strings are isomorphic in nature, a method is defined that takes two strings as parameters. It iterates through the length of the string, and converts a character into an integer using the ‘ord’ method.

## Example

Below is a demonstration of the same

MAX_CHARS = 256

def check_isomorphic(str_1, str_2):
len_1 = len(str_1)
len_2 = len(str_2)

if len_1 != len_2:
return False

marked = [False] * MAX_CHARS
map = [-1] * MAX_CHARS

for i in range(len_2):

if map[ord(str_1[i])] == -1:

if marked[ord(str_2[i])] == True:
return False

marked[ord(str_2[i])] = True

map[ord(str_1[i])] = str_2[i]

elif map[ord(str_1[i])] != str_2[i]:
return False
return True
str_1 = 'aababa'
str_2 = 'xxyyxx'
print("The first string is :")
print(str_1)
print("The second string is :")
print(str_2)
print("Is the first string isomorphic ?")
print(check_isomorphic("aab","xxy"))
print("Is the second string isomorphic ?")
print(check_isomorphic("aab","xyz"))

## Output

The first string is :
aababa
The second string is :
xxyyxx
Is the first string isomorphic ?
True
Is the second string isomorphic ?
False

## Explanation

• A method named ‘check_isomorphic’ is defined.

• This method takes two strings as parameters.

• It determines the length of the strings.

• It is required to ensure that the strings are not of the same lengths.

• Two lists are created where one contains ‘False’ values and other contains ‘-1’ values.

• The second string length is iterated over, and the first string’s characters are converted into integer.

• Corresponding value in the list with ‘False’ values is changed.

• Outside the function, two strings are defined, and are displayed on the console.

• The method is called by passing these strings as parameters.

• The output is displayed on the console.

Published on 20-Sep-2021 11:08:09