敏感词匹配-前缀树(c++/go/lua)

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听音乐就好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值