Python 查找字符串是否是彼此字符串的变位词

标签 python algorithm while-loop

我正在尝试解决上述面试问题,以检查字符串是否是彼此的变位词。实现如下:

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/

相关文章:

Python UDP 套接字服务器

java - 树的层序遍历

algorithm - 递归伸展树(Splay Tree)

c++ - 所有子串的频率

java - 如何在 Eclipse 中定义 While(boolean) 循环

关于 'while + read' .vs. 的性能问题AWK

python - 如何将字符串转换为嵌套列表,元素以逗号分隔

javascript - 使用 ionic、Angular 和 django+rest 框架上传图像

python - 如何创建一个空的 zip 文件?

c++ - 简单文件 I/O 程序 C++