`
128kj
  • 浏览: 583775 次
  • 来自: ...
社区版块
存档分类
最新评论

深度优先遍历字典树(统计单词出现的个数)

阅读更多
例:给出一个字符文本,每行一个字符串,统计不同的字符串出现的百分比,最后按ASCII排序输出不同字符串和出现的百分比。

分析:对输入字符串建立字典树,在叶子结点记录该字符串出现的次数。这样的话,最后DFS搜索就可以查找每个字符串出现的次数。
样例:
Sample Input

Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
exit

Sample Output

Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483

import java.util.Scanner;
import java.text.DecimalFormat; 

class Trie{ //字典树
    Trie next[] = new Trie[128];//所有儿子节点
    int cnt;/* 用于记录单词出现的次数,若cnt大于0,说明  
                 从根节点到此节点的父节点构成了一个单词,这个  
                 单词的次数就是cnt */  
    public Trie(){
        cnt = 0;
    }
} 
 
public class Main{ 
    Trie root = new Trie();
    String res;
    int all = 0;
    DecimalFormat a = new DecimalFormat("0.0000");
    void solve() {
        Scanner  cin = new Scanner(System.in);
      
        String input;
        while(cin.hasNext()){//用所有字符串,构造字典树
            input = cin.nextLine();
           // if(input.equals("exit")) break;
            insert(input.toCharArray());
        }
        res = "";
        dfs(root);//深度优先搜索字典树
    }
    void insert(char[] str){//将一个字符串插入字典树
        int len = str.length;
        int k = 0, t;
        Trie p = root;
        while(k!=len){
            t = str[k++];
            if(p.next[t] == null) p.next[t] = new Trie();
            p = p.next[t];
        }
        p.cnt++;//字符串的最后一个节点,根节点到此节点构成了一个单词,此单词的个数加1
        all++;//字符串总数加1
    }
     
    void dfs(Trie p){
        if(p.cnt!=0) System.out.println(res + " " + a.format(p.cnt*100.0/all));
        for(int i=0;i< 128;i++){//遍历p的所有儿子节点(邻接点)
            if(p.next[i] != null){
                res+=(char)i;
                dfs(p.next[i]);
                res = res.substring(0, res.length()-1);//恢复现场
            }
        }
    }
    public static void main(String[] args) {
        Main test = new Main();
         test.solve();
    }
}


源码:
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics