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”值的列表中的对应值。
在函数外部,定义两个字符串,并在控制台中显示。
通过将这些字符串作为参数来调用该方法。
输出显示在控制台中。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP