// 插入一个模式串 voidinsert(const string& pattern, int id){ int cur = 0; for (char ch : pattern) { int c = ch - 'a'; if (trie[cur].next[c] == -1) { trie[cur].next[c] = trie.size(); trie.emplace_back(); } cur = trie[cur].next[c]; } trie[cur].output.push_back(id); }
// 构建失败指针 voidbuild_fail(){ queue<int> q; for (int c = 0; c < ALPHABET; c++) { int nxt = trie[0].next[c]; if (nxt != -1) { trie[nxt].fail = 0; q.push(nxt); } else { trie[0].next[c] = 0; // root 自环 } }
while (!q.empty()) { int u = q.front(); q.pop(); for (int c = 0; c < ALPHABET; c++) { int v = trie[u].next[c]; if (v == -1) continue;
int f = trie[u].fail; while (trie[f].next[c] == -1) { f = trie[f].fail; } trie[v].fail = trie[f].next[c];
// 继承 fail 指针的输出结果 for (int id : trie[trie[v].fail].output) { trie[v].output.push_back(id); }
q.push(v); } } }
// 匹配主串中的所有位置 voidsearch(const string& text){ int cur = 0; for (int i = 0; i < text.size(); ++i) { int c = text[i] - 'a'; while (trie[cur].next[c] == -1) { cur = trie[cur].fail; } cur = trie[cur].next[c];
for (int id : trie[cur].output) { cout << "匹配到模式串 #" << id << " : " << patterns[id] << " at position " << i - patterns[id].size() + 1 << endl; } } }
// 示例用法 intmain(){ patterns = {"he", "she", "his", "hers"}; for (int i = 0; i < patterns.size(); ++i) { insert(patterns[i], i); }
voidinsert(const string& word){ TrieNode* node = root; for (char ch : word) { int idx = ch - 'a'; if (!node->children[idx]) node->children[idx] = newTrieNode(); node = node->children[idx]; } node->output.push_back(word); }
voidbuild(){ queue<TrieNode*> q;
// Initialize fail pointers of root's children for (int i = 0; i < ALPHABET_SIZE; i++) { if (root->children[i]) { root->children[i]->fail = root; q.push(root->children[i]); } }
while (!q.empty()) { TrieNode* current = q.front(); q.pop();
for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode* child = current->children[i]; if (!child) continue;
if (matched.empty()) { cout << "No patterns matched.\n"; } else { cout << "Matched patterns:\n"; for (const string& word : matched) { cout << word << endl; } }
return0; }
示例输出输入,我就拿无耻之徒里lan和lip的对话举例子了,没办法,这电视剧太能爆粗口了。 Enter number of patterns: 5 Enter patterns: fuck shit asshole joke stupid Enter text: You must be joking! You’re fucking him?! Him?! He’s married. With kids! What else does he buy you, Ian?” “Listen to me, stupid! You think you know everything, and you don’t know shit…” “Fucking kept boy, at best.” “You smart asshole! Go back there now. Promise Kash you’ll keep your mouth shut… because he’s shitting himself. Matched patterns: fuck stupid shit fuck asshole shit