我在一次采访中收到了这个问题,并编码出了一个解决方案,但它并不是最优的.
给出一系列的单词,如:
军队,拉米,cat ,吃,茶……
How can you store these words to support the following query:
Given a word return list of anagrams present in the stream实施方法:
public void storeWords(String[] words); public String[] getAnagrams(String word);
例如:
getAnagrams("army")
会返回["army", "ramy"]
getAnagrams("tac")
会返回["cat"]
我需要它有O(1)的时间复杂度来查找getAnagram(),这意味着StoreWords()需要以一种不需要循环查找的方式来存储字形.目前,我的解决方案的运行时间为O(N)次,因为我使用的是循环.我不确定如何着手优化这一点.我在想也许可以使用Trie,但我不知道如何使用它来给我一个O(1)解
我的解决方案是:
- 创建一个Anagram_map,该映射接受其Unicode数字的key:sum和,以及具有该Unicode和的单词列表
- ex.类别将是关键字:顺序(C)+顺序(A)+顺序(T)和值:[类别]
- GetAnagram将从传入的单词的Unicode数字总和中获取可能的字谜列表.然后,我有一个isAnagram的帮助器函数,它判断单词是否是给定单词的变形词
- IsAnagram有一个 map ,可以统计字形和单词的字数.如果 map 中的所有内容的计数都为0,则它是字谜
- 将其追加到我们返回的列表中
我的代码如下:
from collections import defaultdict
class Anagram:
def __init__(self):
self.anagram_map = defaultdict(list)
def storeWords(self, words):
for word in words:
unicode_sum = 0
for c in word:
unicode_sum += ord(c)
self.anagram_map[unicode_sum].append(word)
def getAnagrams(self, word):
unicode_sum = 0
res = []
for c in word:
unicode_sum += ord(c)
anagrams = self.anagram_map[unicode_sum]
for anagram in anagrams:
if self.isAnagram(anagram.word):
res.append(anagram)
return res
def isAnagram(self, anagram, word):
count_map = {}
for c in anagram:
if c in count_map:
count_map[c] += 1
else:
count_map[c] = 1
for w in word:
if w in count_map:
count_map[w] -= 1
else:
return False
for count in count_map.values():
if count != 0:
return False
return True
anagram = Anagram()
stream = ['army', 'ramy', 'cat', 'eat','tea']
anagram.storeWords(stream)
print(anagram.getAnagrams('army'))
print(anagram.getAnagrams('tac'))
有人知道我怎样才能优化这一点吗?