什么是检查字谜的更优雅的方法?

时间:2019-05-08 18:50:20

标签: anagram

我无法想象有比我的解决方案更好的方法来检查字谜:

def anagram(self,s,t):
        if len(s) != len(t):
            return False
        else:
            for elem1 in s:
                current_looking = elem1            
                if current_looking in t:
                    current_index = t.index(current_looking)
                    t = t[:current_index] + t[current_index+1:]
                else:
                    return False
            return True

或者这个:

def anagram(s1,s2):
   return sorted(s1) == sorted(s2)

也许还有另一个?

1 个答案:

答案 0 :(得分:1)

collections.Counter比排序方法简洁(O(n)

from collections import Counter

def anagram(a, b):
    return Counter(a) == Counter(b)

您可以牺牲简洁性来提高性能:

def anagram(a, b):
    return len(a) == len(b) and Counter(a) == Counter(b)