生活随笔
收集整理的這篇文章主要介紹了
java字典树(Trie)实现中文模糊匹配
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
原理解釋:
java實(shí)現(xiàn):https://blog.csdn.net/yuhk231/article/details/51539840
c實(shí)現(xiàn):https://blog.csdn.net/qq_31175231/article/details/77827324
代碼模板:缺點(diǎn),只能檢索出在一個(gè)分支中的前綴匹配內(nèi)容
package com.xq.algorithm;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;/** 無(wú)數(shù)據(jù)結(jié)構(gòu)設(shè)計(jì)下的蠻力中文鍵樹*/
class TrieNode {public String value;public ArrayList<TrieNode> ptr = null;public TrieNode(String value) {this.value=value;ptr =new ArrayList<TrieNode>();}
}public class TrieTree_1 {private static TrieNode root = null;ArrayList<String> searchResult=new ArrayList<String>();StringBuffer tempWord=new StringBuffer();int start=0;public TrieTree_1() {root = new TrieNode(null);}public void insert(String key) {TrieNode p = root;String tempWord;boolean contains;TrieNode tempNode;for (int i = 0; i < key.length(); i++) {tempWord=String.valueOf(key.charAt(i));contains=false;for(TrieNode tn:p.ptr){if(tn.value.equals(tempWord)){p=tn;contains=true;break;}}if(!contains){tempNode=new TrieNode(tempWord);p.ptr.add(tempNode);p=tempNode;}}}public ArrayList<String> search(String key) { //模糊查詢就是這個(gè)方法,打個(gè)比方比如key是"ap",那么ArrayList里就有{"apple","application"}TrieNode p = root;String temp;boolean contains=false;for (int i = 0; i < key.length(); i++) {temp=String.valueOf(key.charAt(i));contains=false;for(TrieNode tn:p.ptr){if(tn.value.equals(temp)){p=tn;contains=true;break;}}if(contains){continue;}else{break;}}if(contains){if(!(p.ptr.isEmpty())){//查找到關(guān)鍵字searchResult.clear();tempWord.delete(0, tempWord.length());tempWord.append(key);start=key.length();traverseTree(p);}else{//已經(jīng)查找到鍵樹的底部return null;}}else{//沒(méi)有查找到相應(yīng)關(guān)鍵字return null;}return searchResult;}private void traverseTree(TrieNode p){if(!(p.ptr.isEmpty())){for(TrieNode tn:p.ptr){tempWord.append(tn.value);start++;traverseTree(tn);start--;tempWord.delete(start,tempWord.length());}}else{searchResult.add(tempWord.toString());}}public static void main(String[] args) {TrieTree_1 chinese = new TrieTree_1();chinese.insert("中");chinese.insert("中國(guó)人");chinese.insert("中國(guó)");chinese.insert("中華人民");chinese.insert("中華人崛起");chinese.insert("中華上下五千年");ArrayList<String> list = chinese.search("中華");for (String string : list) {System.out.println(string);}}
}
總結(jié)
以上是生活随笔為你收集整理的java字典树(Trie)实现中文模糊匹配的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。