简体   繁体   English

Python查找字符串是否彼此串字

[英]Python find if strings are anagram of each other string

I am trying to solve the above interview question to check if string are anagram of each other. 我正在尝试解决上面的面试问题,以检查字符串是否彼此相似。 The implementation is as follows: 实现如下:

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"

I am getting the following error while running the code: 运行代码时出现以下错误:

TypeError: 'In <string> requires string as left operand

Am I doing something wrong in the while loop? 我在while循环中做错什么了吗? Also, how can I avoid to use i = 0 statement? 另外,如何避免使用i = 0语句? Thanks. 谢谢。

An easy way to see if strings are comprised of the same characters is to compare them as sorted lists: 查看字符串是否包含相同字符的一种简单方法是将它们作为排序列表进行比较:

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)

If you want to go for counting the characters, you need to make counts for both strings and compare them 如果要对字符进行计数,则需要对两个字符串进行计数并进行比较

NO_OF_CHARS = 256
def areAnagram(str1, str2):
    if len(str1) != len(str2):
        return 0
    count = [0] * NO_OF_CHARS
    for c1,c2 in zip(str1,str2):
        count[ord(c1)] +=1
        count[ord(c2)] -=1
    return all(not c for c in count)

I moved checking the length of strings to the beginning of the method for efficiency and clarity 我将检查字符串的长度移到方法的开头,以提高效率和清晰度

EDIT: Updated my answer according to Blckknght's comment 编辑:根据Blckknght的评论更新了我的答案

The canonical way to do this in Python is to use collections.Counter : 在Python中执行此操作的规范方法是使用collections.Counter

from collections import Counter

def areAnagram(str1, str2):
    return Counter(str1) == Counter(str2)

This should take O(N) space and time (where N is max(len(str1), len(str2)) ). 这应该占用O(N)空间和时间(其中Nmax(len(str1), len(str2)) )。 But do be aware that even though this code's asymptotic performance is better, it may still be slower for short strings than a version using sorted . 但是请注意,即使这段代码的渐近性能更好,但短字符串的性能可能仍比使用sorted的版本慢。 Python's sort code is very fast! Python的sort代码非常快!

If you're likely to be using the function to compare very-unlike strings, you could perhaps it up a little bit with a special case checking the string lengths before counting: 如果您可能正在使用该函数比较非常不同的字符串,则可以使用一种特殊情况在计数前检查字符串长度来稍微提高一点:

def areAnagram(str1, str2):
    return len(str1) == len(str2) and Counter(str1) == Counter(str2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM