基于JAVA语言开发的一个高效的敏感词过滤工具
经实测,敏感词数量为5000个,待检测文本长度为200时,此工具类可毫秒级高效检索敏感词
各位同学需要自取,转载请标明出处
package com.wgh.common.utils;
import com.google.common.collect.Lists;
import java.util.*;
/**
* @desc 一个用于敏感词检测的高效工具类
* @author 王冠华
* @date 2024-07-17
*/
public class SensitiveWordFilter {
private static class TrieNode {
Map<Character, TrieNode> children; // 使用 Map 来存储子节点
TrieNode fail; // 失败指针
boolean isEndOfWord; // 标记是否是敏感词的结尾
String word; // 存储完整的敏感词
public TrieNode() {
this.children = new HashMap<>(); // 使用 HashMap 存储子节点
this.fail = null;
this.isEndOfWord = false;
this.word = null;
}
}
private TrieNode root;
/**
* 构造函数,用于初始化敏感词库。
* @param words 敏感词集合,集合确保敏感词不会重复
*/
public SensitiveWordFilter(Set<String> words) {
root = new TrieNode();
addWords(words);
buildFailurePointers();
}
/**
* 将敏感词集合添加到 Trie 树中。
* @param words 敏感词集合
*/
private void addWords(Set<String> words) {
for (String word : words) {
addWord(word.toLowerCase()); // 转换为小写
}
}
/**
* 将单个敏感词添加到 Trie 树中。
* @param word 敏感词
*/
private void addWord(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
current.children.putIfAbsent(c, new TrieNode());
current = current.