过滤敏感字的算法
package testFilter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 算法思路:把敏感词的第一个字符取出来,作为比较对象。 遍历整个字符串,如果发现字符跟敏感词第一个字符相同, * 就从字符串取出跟关键词相同长度的子串比较,如果相同就替换 * * 本算法比较适合敏感词都不长的场合 * * @author Administrator * */ public class WordFilter { private static Map<Character, List<String>> wordListToMap( List<String> sensitiveWordList) { Map<Character, List<String>> result = new HashMap<Character, List<String>>(); for (String s : sensitiveWordList) { char c = s.charAt(0); List<String> strs = result.get(c); if (strs == null) { strs = new ArrayList<String>(); result.put(c, strs); } strs.add(s); } return result; } public static String filter(String src, List<String> sensitiveWordList) { Map<Character, List<String>> wordMap = wordListToMap(sensitiveWordList); StringBuilder strb = new StringBuilder(); for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); String find = null; if (wordMap.containsKey(c)) { List<String> words = wordMap.get(c); for (String s : words) { String temp = src.substring(i, (s.length() <= (src.length() - i)) ? i + s.length() : i); if (s.equals(temp)) { find = s; break; } } } if (find != null) { strb.append("***"); i += (find.length() - 1); } else { strb.append(c); } } return strb.toString(); } /** * @param args */ public static void main(String[] args) { List<String> wordList = new ArrayList<String>(); wordList.add("sensitive"); wordList.add("敏感词"); System.out.println(filter("这是一个简单sensitive的filter实例", wordList)); System.out.println(filter("sensitivesensiti这是一个sensitive敏感词简单的filter实例敏感词", wordList)); System.out.println(filter("这是一个sensitive简单的filter实例敏感词", wordList)); System.out.println(filter("敏感词这是一个sensitive简单的filter实例sensitive敏感词", wordList)); System.out.println(filter("敏感词这是一个敏感简单的filter实例sensitive敏感词", wordList)); wordList.add("敏感"); System.out.println(filter("敏感词这是一个敏感简单的filter实例sensitive敏感词", wordList)); } }
输出:
这是一个简单***的filter实例
***sensiti这是一个******简单的filter实例***
这是一个***简单的filter实例***
***这是一个***简单的filter实例******
***这是一个敏感简单的filter实例******
***这是一个***简单的filter实例******
相关推荐
taishanduba 2020-09-12
sunnyJam 2019-12-03
haohong 2019-10-29
natloc 2011-12-27
燕哥带你学算法 2019-06-29
cuiweisaidelike 2010-12-07
luokingfly 2018-09-24
crayydog 2018-10-26
郭岚 2018-07-24
展翅飞翔phpBoy00 2019-04-17