javatrie_java字典树(Trie)实现中⽂模糊匹配package com.xq.algorithm;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
/*
* ⽆数据结构设计下的蛮⼒中⽂键树
*/
class TrieNode {
public String value;
public ArrayList ptr = null;
public TrieNode(String value) {
this.value=value;
ptr =new ArrayList();
}
}
public class TrieTree_1 {
private static TrieNode root = null;
ArrayList archResult=new ArrayList();
StringBuffer tempWord=new StringBuffer();
int start=0;
public TrieTree_1() {
root = new TrieNode(null);
}
public void inrt(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));normally
contains=fal;
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 arch(String key) { //模糊查询就是这个⽅法,打个⽐⽅⽐如key是"ap",那么ArrayList⾥就有{"apple","application"}
TrieNode p = root;
String temp;
boolean contains=fal;
for (int i = 0; i < key.length(); i++) {
bring out
temp=String.valueOf(key.charAt(i));
型号翻译
contains=fal;
for(TrieNode tn:p.ptr){
if(tn.value.equals(temp)){
p=tn;
contains=true;
break;
}
}translate google com
if(contains){
continue;
}el{
break;
}
库存现金管理}
if(contains){
if(!(p.ptr.isEmpty())){dde是什么意思
//查找到关键字
archResult.clear();
tempWord.delete(0, tempWord.length()); tempWord.append(key);
start=key.length();
traverTree(p);
}el{
//已经查找到键树的底部
return null;
}
}el{
//没有查找到相应关键字
return null;
}
return archResult;
}
private void traverTree(TrieNode p){
if(!(p.ptr.isEmpty())){
for(TrieNode tn:p.ptr){
tempWord.append(tn.value);
start++;ction什么意思
traverTree(tn);
start--;
tempWord.delete(start,tempWord.length()); }
}el{
archResult.String());服装店陈列道具
}
}
public static void main(String[] args) { TrieTree_1 chine = new TrieTree_1(); chine.inrt("中");
chine.inrt("中国⼈");
chine.inrt("中国");
chine.inrt("中华⼈民");
best buy
chine.inrt("中华⼈崛起");
chine.inrt("中华上下五千年"); ArrayList list = chine.arch("中华"); for (String string : list) {
uguSystem.out.println(string);
}
}
}