本片文章来源:http://www.story58.com/chtagpt/gpt_index.html 原文有资源可以下载
以下是一个简单的敏感词过滤的实现示例:
-
创建一个Trie树节点类
TrieNode
,每个节点包含一个HashMap
类型的子节点映射和一个布尔值,表示当前节点是否为敏感词的末尾。
-
class TrieNode {
HashMap<Character, TrieNode> children;
boolean isEndOfWord;
TrieNode() {
children = new HashMap<>();
isEndOfWord = false;
}
}
-
构建Trie树,将敏感词逐个插入到树中。
-
class Trie {
TrieNode root;
void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.isEndOfWord = true;
}
}
-
实现敏感词过滤功能,遍历输入的文本,在Trie树中进行匹配。
-
class Filter {
TrieNode root;
boolean filterText(String text) {
TrieNode current = root;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
continue;
}
current = node;
if (current.isEndOfWord) {
return true; // 匹配到敏感词
}
}
return false; // 未匹配到敏感词
}
}
使用示例:
public class Main {
public static void main(String[] args) {
Filter filter = new Filter();
filter.root = new TrieNode();
// 构建敏感词库
filter.insert("敏感词1");
filter.insert("敏感词2");
filter.insert("敏感词3");
// 检查文本是否含有敏感词
boolean hasSensitive = filter.filterText("这是一个包含敏感词1的文本");
System.out.println(hasSensitive); // 输出 true
}
}
这种基于Trie树的敏感词过滤算法具有高效的匹配速度和较小的空间复杂度,但有时需要处理较大的敏感词库时可能会占用较多的内存。