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("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

解釋

  • 定義了一個名為“check_isomorphic”的方法。

  • 此方法將兩個字串作為引數。

  • 它確定字串的長度。

  • 需要確保字串的長度不相等。

  • 建立兩個列表,一個包含“False”值,另一個包含“-1”值。

  • 迭代第二個字串的長度,並將第一個字串的字元轉換為整數。

  • 更改包含“False”值的列表中的對應值。

  • 在函式外部,定義兩個字串,並在控制檯中顯示。

  • 透過將這些字串作為引數來呼叫該方法。

  • 輸出顯示在控制檯中。

更新於:2021年9月20日

249 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告