好的,我要提出一些奇怪的东西,但是来自C++ 我已经使用Boost 很长时间了,我是来看MultiIndex 库的。
这个库的想法是创建一个集合,但有许多不同的方式来查询它。实际上,它可以建模一个数据库。
所以,让我们把我们的话放在一个表中,并把必要的索引放在适当的位置:
word |length|c0|c1|c2| ... |c26|
-------------------------|------|--|--|--| ... |---|
Singapour |9 |S |i |n | ... |0 |
现在查询将如下所示:
Select word From table Where length=9 And c2='n' And c8='u';
是不是很简单?
为获得最大效率,表应按长度分区,索引(每 cX 列一个)应在分区本地。
对于内存解决方案,每个长度都有一个容器,包含与长度一样多的索引,每个索引都是指向排序列表的哈希表(更容易合并)
这是一个python描述:
class Dictionary:
def __init__(self, length):
self.length = length
self.words = set([])
self.indexes = collections.defaultdict(set)
def add(self, word):
if len(word) != self.length:
raise RuntimeException(word + ' is not ' + `self.length` + ' characters long')
if word in self.words:
raise RuntimeException(word + ' is already in the dictionary')
self.words.add(word)
for i in range(0,length):
self.indexes[(i,word[i])].add(word)
def search(self, list):
"""list: list of tuples (position,character)
"""
def compare(lhs,rhs): return cmp(len(lhs),len(rhs))
sets = [self.indexes[elem] for elem in list]
sets.sort(compare)
return reduce(intersection, sets)
我自愿提供了length 参数,以最小化散列的大小,从而使搜索更好。此外,集合按长度排序,以便更好地计算交集:)
如果您愿意,可以继续使用其他解决方案对其进行测试 :)