一共命中多少处
四个要找的词 he、she、his、hers,一段文本 ushershishe(11 个字符,下标从 0 起):
WORDS = ['he', 'she', 'his', 'hers']
TXT = "ushershishe"
def build(words):
t = {}
for w in words:
node = t
for ch in w:
node = node.setdefault(ch, {})
node["#"] = w
return t
def scan(t, txt):
"""从每个起点顺着 Trie 往下走,走到 # 就记一个命中"""
hits = []
for i in range(len(txt)):
node = t
for j in range(i, len(txt)):
if txt[j] not in node:
break
node = node[txt[j]]
if "#" in node:
hits.append((i, node["#"]))
return sorted(hits)
t = build(WORDS)
print(len(scan(t, TXT)))
全部评论