Python - 检查两个字符串是否本质上是同构的

当需要检查两个字符串本质上是否同构时,定义了一个以两个字符串作为参数的方法。它遍历字符串的长度,并使用 'ord' 方法将字符转换为整数。

示例

下面是相同的演示

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("第一个字符串是:")
print(str_1)
print("第二个字符串是:")
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"))
输出结果
第一个字符串是:
aababa
第二个字符串是:
xxyyxx
Is the first string isomorphic ?
True
Is the second string isomorphic ?
False

解释

  • 定义了一个名为“check_isomorphic”的方法。

  • 该方法以两个字符串作为参数。

  • 它决定了字符串的长度。

  • 需要确保字符串的长度不同。

  • 创建了两个列表,其中一个包含“False”值,另一个包含“-1”值。

  • 迭代第二个字符串长度,并将第一个字符串的字符转换为整数。

  • 列表中带有 'False' 值的相应值已更改。

  • 在函数外部,定义了两个字符串,并显示在控制台上。

  • 通过将这些字符串作为参数传递来调用该方法。

  • 输出显示在控制台上。

猜你喜欢