JAVA 实现DFA算法

1、创建敏感字Map

public static Map addWordToHashMap(Set<String> keyWordSet) {
        if(0 == keyWordSet.size()) return new HashMap();
        Map map = new HashMap(keyWordSet.size());
        String key = null;
        Map nowMap = null;
        Map<String, String> newWorMap = null;
        Iterator<String> iterator = keyWordSet.iterator();
        while(iterator.hasNext()){
            key = iterator.next();
            nowMap = map;
            for(int i = 0; i < key.length(); i++){
                char keyChar = key.charAt(i);
                Map wordMap = (Map) nowMap.get(keyChar);
                if(wordMap != null) nowMap =  wordMap;
                else{
                    newWorMap = new HashMap<String,String>();
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }
                if(i == key.length() - 1) nowMap.put("isEnd", "1");
            }
        }
        return map;
    }

 

2、创建正则特殊符号过滤

public static String formatString(String str) {
        if (StringUtils.isNotBlank(str)) {
            String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
            return   Pattern.compile(regEx).matcher(str).replaceAll("").trim();
        }
        return "";
    }

 

3、校验字符串

 

public static String checkWork(String txt, Map map, boolean needToFormat) {
        try {
            if (needToFormat) txt = formatString(txt);
            StringBuffer sb = new StringBuffer();
            boolean has = false;
            char word;
            int num;
            for (int i = 0; i < txt.length(); i++) {
                word = txt.charAt(i);
                sb = new StringBuffer(word);
                if (map.containsKey(word)) {
                    Map m = (Map) map.get(word);
                    sb.append(word);
                    num = i + 1;
                    while (true) {
                        if (num < txt.length()) {
                            word = txt.charAt(num++);
                            sb.append(word);
                            if (m.containsKey(word)){
                                m = (Map) m.get(word);
                                if (m.containsKey("isEnd")) {
                                    has = true;
                                    return sb.toString();
                                }
                            } else break;
                        } else break;
                    }
                }
            }
            if (has)  return sb.toString();
        } catch (Exception e) {
            //logger.error("检验敏感字出错,原因为:{}", e);
            e.printStackTrace;
        }
        return null;
    }
 

 

 

转载于:https://my.oschina.net/u/2376377/blog/827215

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值