我有一个简单的变位问题,在这个问题中我将得到一个单词和另一个单词列表。在这个单词列表中,我必须找出其中哪些是第一个单词的变位词。
因此,我检查了互联网并提出了两个解决方案,如下所述:
解决方案1:
from collections import counter
def checkAnagram(word,words):
anagrams = []
for w in words:
if len(w) != len(word):
return False
elif w == word:
return False
else:
if counter(word) == counter(w):
anagrams.append(word)
else:
return False
return anagrams
解决方案2:
def anagramSolution4(s1,s2):
c1 = [0]*26
c2 = [0]*26
for i in range(len(s1)):
pos = ord(s1[i])-ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i])-ord('a')
c2[pos] = c2[pos] + 1
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]!=c2[j]:
return False
def checkAnagram(word,words):
anagrams = []
for w in words:
if anagramSolution4(word,w):
anagrams.append(w)
return anagrams
我的问题似乎都在使用O(NM)复杂性,对吧?这里n是输入词的大小,m是一个词的最大大小。
如果有更好的解决方案使用更少的复杂性,有人能指出我吗?
事先谢谢。