標籤:
class Trie{private int SIZE=26;private TrieNode root;//字典樹的根Trie(){//初始化字典樹root=new TrieNode();}private class TrieNode{//字典樹節點private int num;//有多少單詞通過這個節點,即節點字元出現的次數private TrieNode[] son;//所有的兒子節點private boolean isEnd;//是不是最後一個節點private char val;//節點的值TrieNode(){num=1;son=new TrieNode[SIZE];isEnd=false;}}//建立字典樹public void insert(String str){//在字典樹中插入一個單詞if(str==null||str.length()==0){return ;}TrieNode node=root;char[] letters=str.toCharArray();for(int i=0,len=str.length();i < len;i++){int pos=letters[i]-'a';if(node.son[pos]==null){node.son[pos]=new TrieNode();node.son[pos].val=letters[i];}else{node.son[pos].num++;}node=node.son[pos];}node.isEnd=true;}//計算單詞首碼的數量public int countPrefix(String prefix){if(prefix==null || prefix.length()==0){return -1;}TrieNode node=root;char[] letters=prefix.toCharArray();for(int i=0,len=prefix.length();i<len;i++){int pos=letters[i]-'a';if(node.son[pos]==null){return 0;}else{node=node.son[pos];}}return node.num;}//在字典樹中尋找一個完全符合的單詞.public boolean has(String str){if(str==null || str.length()==0){return false;}TrieNode node=root;char[] letters = str.toCharArray();for(int i=0,len=str.length();i<len;i++){int pos= letters[i]-'a';if(node.son[pos]!=null){node=node.son[pos];}else{return false;}}return node.isEnd;}//前序走訪字典樹.public void preTraverse(TrieNode node){if(node!=null){System.out.print(node.val+"-");for(TrieNode child:node.son){preTraverse(child);}}}public TrieNode getRoot(){return this.root;}public static void main(String[] args){Trie tree=new Trie();String[] strs={"banana","band","bee","absolute","acm",};String[]prefix={"ba","b","band","abc",};for(String str:strs){tree.insert(str);}System.out.println(tree.has("abc"));tree.preTraverse(tree.getRoot());System.out.println();for(String pre:prefix){int num=tree.countPrefix(pre);System.out.println(pre+" "+num);}}}
具體看百科:http://baike.baidu.com/link?url=bImDvvYau9FWbZKr64ExkxvXOZb_Df-b7O2YCPHyqH_orknkoOi6JT4O-3a9XqorwbugAnTibEq0pFjx-Gvu8_
字典樹模板(java)