我无法想象有比我的解决方案更好的方法来检查字谜:
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)
也许还有另一个?
答案 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)