字典樹模板(java)

來源:互聯網
上載者:User

標籤:

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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.