สตริงสองสตริงจะเป็น Isomorphic ถ้าสามารถจับคู่ตัวอักษรจากสตริงแรกไปสตริงที่สองได้แบบหนึ่งต่อหนึ่ง (One-to-one mapping) โดยตัวอักษรเดียวกันในสตริงแรกต้องแมปไปตัวอักษรเดียวกันในสตริงที่สองเสมอ และตัวอักษรต่างกันต้องแมปไปตัวอักษรที่ต่างกัน
ตัวอย่างโค้ด
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"))
ผลลัพธ์
The first string is : aababa
The second string is : xxyyxx
Is the first string isomorphic ? True
Is the second string isomorphic ? False
คำอธิบาย
- ตรวจสอบความยาวก่อน ถ้าไม่เท่ากันคืน
Falseทันที - ใช้ Array
markedติดตามตัวอักษรใน str_2 ที่ถูกแมปไปแล้ว - ใช้ Array
mapเก็บการแมปจาก str_1 ไป str_2 (เก็บเป็นค่า ASCII) - วนลูปตรวจสอบการแมปซ้ำและความสอดคล้อง