java 数据结构源码--Trie树

node 

package trieTree;

public class TrieTreeNode {
	final int MAX_SIZE=26; 
	int nCount;//记录该字符出现次数  
    char ch; //记录该字符  
    TrieTreeNode[] child;  
      
    public TrieTreeNode() {  
        nCount=1;  
        child=new TrieTreeNode[MAX_SIZE];  
    }  

}

tree

package trieTree;
import trieTree.TrieTreeNode;

public class TrieTree {
	
    //字典树的插入和构建  
    public void createTrie(TrieTreeNode node,String str){  
        if (str==null||str.length()==0) {  
            return;  
        }  
        char[] letters=str.toCharArray();  
        for (int i = 0; i < letters.length; i++) {  
            int pos = letters[i] - 'a';    
            if (node.child[pos] == null) {    
                node.child[pos] = new TrieTreeNode();     
            }else {  
                node.child[pos].nCount++;  
            }  
            node.ch=letters[i];              
            node = node.child[pos];              
        }  
    }  
    //字典树的查找  
    public int findCount(TrieTreeNode node,String str){  
        if (str==null||str.length()==0) {  
            return -1;  
        }  
        char[] letters=str.toCharArray();  
        for (int i = 0; i < letters.length; i++) {  
            int pos = letters[i] - 'a';    
            if (node.child[pos] == null) {    
                return 0;     
            }else {  
                node=node.child[pos];  
            }             
        }  
        return node.nCount;  
    }  

}

测试源码 test

package trieTree;
import trieTree.TrieTree;
import trieTree.TrieTreeNode;

public class test {
	
	 public static void main(String[] args)
	 {
	
	String[] strs={     
            "banana",     
            "band",     
            "bee",     
            "absolute",     
            "acm",     
    };     
    String[] prefix={     
        "ba",     
        "b",     
        "band",     
        "abc",     
    }; 
    
    TrieTree tree = new TrieTree();  
    TrieTreeNode root=new TrieTreeNode();
    
 for (String s : strs) {    
        tree.createTrie(root, s);    
    }     
//    tree.printAllWords();     
    for(String pre:prefix){     
        int num=tree.findCount(root,pre);     
        System.out.println(pre+" "+num);     
    }  
	
}
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/judyge/article/details/41249743
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞