com.luhuiguo.chinese.Trie Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of chinese-utils Show documentation
Show all versions of chinese-utils Show documentation
A Java library supporting conversion between Simplified-Chinese, Traditional-Chinese
and Chinese-Pinyin.
The newest version!
/**
* File : Trie.java
* Created : 2014年1月20日
* By : luhuiguo
*/
package com.luhuiguo.chinese;
/**
*
* @author luhuiguo
*/
public class Trie {
private TrieNode root = new TrieNode(' ');
public Trie() {
super();
}
public void add(char[] w, T value) {
if (w.length < 1) {
return;
}
TrieNode p = root;
for (int i = 0; i < w.length; i++) {
TrieNode n = p.child(w[i]);
if (n == null) {
n = p.addChild(w[i]);
}
p = n;
}
p.setLeaf(true);
p.setValue(value);
}
public void add(String w, T value) {
if (null == w) {
return;
}
add(w.toCharArray(), value);
}
public TrieNode match(char[] sen, int offset, int len) {
TrieNode node = root;
for (int i = 0; i < len; i++) {
node = node.child(sen[offset + i]);
if (node == null) {
return null;
}
}
return node;
}
public TrieNode bestMatch(char[] sen, int offset, int len) {
TrieNode ret = null;
TrieNode node = root;
for (int i = offset; i < len; i++) {
node = node.child(sen[i]);
if (node != null) {
if (node.isLeaf()) {
ret = node;
}
} else {
break;
}
}
return ret;
}
public TrieNode bestMatch(char[] sen, int offset) {
return bestMatch(sen, offset, sen.length);
}
}