TrieTree是字典树,在文本处理中非常好用。
先建立节点
/**
* Created by kyle on 2016/6/23.
*/
public class TrieNode {
private final static int NUMBER = 26;
private char _value ;
private boolean isWorld;
private TrieNode[] _children = new TrieNode[NUMBER];
public TrieNode(char _value) {
this._value = _value;
for(TrieNode tn : _children){
tn = null;
}
isWorld = false;
}
public boolean isWorld() {
return isWorld;
}
public void setWorld(boolean world) {
isWorld = world;
}
public char get_value() {
return _value;
}
public void set_value(char _value) {
this._value = _value;
}
public TrieNode[] getChildren() {
return _children;
}
}
import java.util.Arrays;
import java.util.Stack;
/**
* Created by kyle on 2016/6/23.
*/
public class TrieTree {
TrieNode _root;
public TrieTree() {
this._root =new TrieNode(' ');
}
public void insertIntoTree(String _word) {//插入一个单词
if(_root == null || _word == null || _word.equals("")){
return;
}
char[] cs = _word.toCharArray();
TrieNode current = _root;
for(int i = 0; i< cs.length ; i++){
int offset = (cs[i]- 'a');
if(current.getChildren()[offset] == null){
current.getChildren()[offset] = new TrieNode(cs[i]);
}
current = current.getChildren()[offset];
}
current.setWorld(true);
}
private void _printTree(TrieNode root, Stack<Character> stack){
if(root == null){
return;
}
stack.push(root.get_value());
if(root.isWorld()){
System.out.println(stack.toString());
}
for(TrieNode trieNode : root.getChildren()){
_printTree(trieNode, stack);
}
stack.pop();
}
public void printTree(){
Stack<Character> stack = new Stack<>();
_printTree(_root,stack);
}
public boolean searchWord(String _word){
if(_root == null || _word == null || _word.equals("")){
return false;
}
char[] cs = _word.toCharArray();
TrieNode current = _root;
for(int i = 0; i< cs.length ; i++){
int offset = (cs[i]- 'a');
if(current.getChildren()[offset] == null){
return false;
}else {
current = current.getChildren()[offset];
}
}
// if(current.get_value() == cs[cs.length-1]){
// return true;
// }
return current.isWorld();
// if(current.isWorld() == true){
// return true;
// }
// return false;
}
public boolean deletWord(String _word){
if(_root == null || _word == null || _word.equals("")){
return false;
}
char[] cs = _word.toCharArray();
TrieNode current = _root;
for(int i = 0; i< cs.length ; i++){
int offset = (cs[i]- 'a');
if(current.getChildren()[offset] == null){
return false;
}else {
current = current.getChildren()[offset];
}
}
return true;
}
}
相关测试为:
/**
* Created by kyle on 2016/6/23.
*/
public class Main {
public static void main(String[] args){
System.out.println("hello");
String[] words={"hello", "hi", "what", "how", "wow", "he", "heel"};
TrieTree trieTree = new TrieTree();
for(String word: words){
trieTree.insertIntoTree(word);
}
trieTree.printTree();
System.out.println(trieTree.searchWord("he"));
}
}