如果通过重新排列一个字符串中的字符可以形成另一个字符串,那么这两个字符串就被认为是易位词(anagram)。例如,Race 和 Care。这里,通过重新排列 Care 的字符,我们可以形成 Race。
使用 sorted() 检查两个字符串是否为易位词的 Python 程序
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
输出
race and care are anagram.
我们首先将字符串转换为小写。这是因为 Python 是大小写敏感的(即,Python 中 `R` 和 `r` 是两个不同的字符)。
这里,
如果排序后的数组相等,则字符串是易位词。
另请阅读