【发布时间】:2017-01-16 19:54:32
【问题描述】:
这个问题指的是this problem on lintcode。我有一个可行的解决方案,但是对于庞大的测试用例来说需要很长时间。我想知道如何改进?也许我可以减少在外循环中进行的比较次数。
class Solution:
# @param strs: A list of strings
# @return: A list of strings
def anagrams(self, strs):
# write your code here
ret=set()
for i in range(0,len(strs)):
for j in range(i+1,len(strs)):
if i in ret and j in ret:
continue
if Solution.isanagram(strs[i],strs[j]):
ret.add(i)
ret.add(j)
return [strs[i] for i in list(ret)]
@staticmethod
def isanagram(s, t):
if len(s)!=len(t):
return False
chars={}
for i in s:
if i in chars:
chars[i]+=1
else:
chars[i]=1
for i in t:
if i not in chars:
return False
else:
chars[i]-=1
if chars[i]<0:
return False
for i in chars:
if chars[i]!=0:
return False
return True
更新:只是添加,而不是寻找内置的pythonic解决方案,例如使用已经优化的Counter。已添加 Mike 的建议,但仍超出时限。
【问题讨论】:
-
I am wondering how can it be improved- 请查看codereview.stackexchange.com - 您的问题可能更适合我们的合作伙伴网站。请查看 CodeReview 的如何先询问,以确保它在那里受到好评。 -
您的方法是否应该返回所有其他字符串的字谜字符串?
-
是的,正确的,任何一对字谜。
-
isanagram方法很复杂,看起来你正在编写 C 代码。这是 python,isanagram 只是return Counter(word1) == Counter(word2)! -
但是你使用了
len。你已经使用了@staticmethod。你已经使用了range。您在哪里以及为什么要区分什么是“内置”和什么不是?