我正在尝试解决上述面试问题,以检查字符串是否是彼此的变位词。实现如下:
NO_OF_CHARS = 256
def areAnagram(str1, str2):
count = [0] * NO_OF_CHARS
i = 0
while (i in str1) and (i in str2):
count[ord(i)]+=1
i += 1
if len(str1) != len(str2):
return 0
for i in xrange(NO_OF_CHARS):
if count[i]:
return 0
return 1
str1 = "geeksforgeeks"
str2 = "forgeeksgeeks"
if areAnagram(str1, str2):
print "The two strings are anagram of each other"
else:
print "The two strings are not anagram of each other"
运行代码时出现以下错误:
TypeError: 'In <string> requires string as left operand
我在 while 循环中做错了什么吗?另外,如何避免使用 i = 0 语句?谢谢。
最佳答案
查看字符串是否由相同字符组成的一种简单方法是将它们作为排序列表进行比较:
def is_anagram(src, trgt):
"""
Determine if trgt is an anagram of src
:param src: (str)
:param trgt: (str)
:returns: (bool) True if trgt is an anagram of src; else False
"""
return sorted(src) == sorted(trgt)
关于Python 查找字符串是否是彼此字符串的变位词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38024714/