c++实现
以下是一个使用 C++ 实现基于前缀树(Trie 树)进行敏感词匹配,并将匹配到的敏感词替换成*
的示例代码,代码中详细展示了前缀树节点结构体、前缀树的构建、敏感词匹配及替换的功能实现,具体如下:
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
// 前缀树节点结构体定义
struct TrieNode {
// 使用无序映射存储子节点,键为字符,值为对应子节点指针
unordered_map<char, TrieNode*> children;
// 标记该节点是否为一个敏感词的结尾
bool isEndOfWord;
TrieNode() : isEndOfWord(false) {}
};
// 前缀树类定义
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
// 向前缀树中插入敏感词的函数
void insert(const string& word) {
TrieNode* node = root;
for (char c : word) {
if (node->children.find(c) == node->children.end()) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->isEndOfWord = true;
}
};
// 利用前缀树进行敏感词匹配并替换的函数
string matchAndReplace(const string& text, Trie& trie) {
string result = text;
int n = text.length();
for (int i = 0; i < n; ++i) {
TrieNode* node = trie.root;
int j = i;
while (j < n && node->children.find(result[j])!= node->children.end()) {
node = node->children[result[j]];
if (node->isEndOfWord) {
// 匹配到敏感词,进行替换
int len = j - i + 1;
for (int k = 0; k < len; ++k) {
result[i + k] = '*';
}
i = j;
break;
}
j++;
}
}
return result;
}
int main() {
Trie trie;
// 插入敏感词
vector<string> sensitiveWords = {"命案", "色情", "暴力"};
for (const string& word : sensitiveWords) {
trie.insert(word);
}
string text = "这是一起命案,还有一些色情内容,要避免暴力行为";
string newText = matchAndRepl