数据结构
public class Word implements Comparable<Word>{
public char c;
public MyList next = new MyList();
public boolean flag = false;
public Word(char c){
this.c = c;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public int compareTo(Word word) {
return c - word.c;
}
}
import java.util.ArrayList;
public class MyList extends ArrayList<Word> {
public Word get(char c) {
for (Word w : this) {
if (w.c == c) {
return w;
}
}
return null;
}
public Word binaryGet(char c) {
int left, right, key;
Word word;
left = 0;
right = this.size() - 1;
while (left <= right) {
key = (left + right) / 2;
word = get(key);
if (word.c == c) {
return word;
} else if (word.c > c) {
right = key - 1;
} else {
left = key + 1;
}
}
return null;
}
public Word add(char c) {
Word word = new Word(c);
super.add(word);
return word;
}
}
具体实现
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Slf4j
public final class SensitiveWordUtil {
public static MyList wordList;
private final static char replace = '*';
private final static char[] skip = new char[]{
'!', '*', '-', '+', '_', '=', ',', '.', '@'
};
public static boolean Filter(String text) {
boolean flag = false;
if (wordList == null || wordList.size() == 0) {
log.info("the table of sensitive word is blank ");
return flag;
}
char[] __char__ = text.toCharArray();
int i, j;
Word word;
endLoop:
for (i = 0; i < __char__.length; i++) {
char c = __char__[i];
word = wordList.binaryGet(c);
if (word != null) {
if (word.flag) {
flag = true;
break;
}
j = i + 1;
while (j < __char__.length) {
if (skip(__char__[j])) {
j++;
continue;
}
word = word.next.get(__char__[j]);
if (word == null) {
break;
}
if (word.flag) {
flag = true;
break endLoop;
}
j++;
}
}
}
return flag;
}
public static void loadWord(List<String> words) {
if (words == null) {
return;
}
char[] chars;
MyList now;
Word word;
wordList = new MyList();
for (String __word__ : words) {
if (StrUtil.isBlank(__word__)) {
continue;
}
chars = __word__.toCharArray();
now = wordList;
word = null;
for (char c : chars) {
if (word != null) {
if (word.next == null) {
word.next = new MyList();
}
now = word.next;
}
word = now.get(c);
if (word == null) {
word = now.add(c);
}
}
if (Objects.nonNull(word)) {
word.setFlag(true);
}
}
sort(wordList);
}
private static void sort(MyList list) {
if (list == null) {
return;
}
Collections.sort(list);
for (Word word : list) {
sort(word.next);
}
}
private static boolean skip(char c) {
for (char c1 : skip) {
if (c1 == c) {
return true;
}
}
return false;
}
}