Trie树:统计词频、排序、查找

Trie树利用字符串的公共前缀降低了查询时间的开销,提高了查询的效率。

字典树的插入,删除和查找都非常简单,用一个一重循环即可。

1. 从根节点开始一次搜索

2. 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索

3. 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索

4. 迭代过程...

5. 在某个节点处,关键词的所有字母已被取出,则读取附在该节点上的信息,即完成查找

package algrithm;

public class dictionaryTree2 {

	private int SIZE=26;
	private TreeNode root;//字典的根
	
	public dictionaryTree2() {
		// TODO Auto-generated constructor stub
		root=new TreeNode();
	}
	
	private class TreeNode
	{
		 private int num; //词频统计
		 private TreeNode []son;//每一层都是由26字母开头的,即所有的节点
		 private boolean isWord;//是不是最后一个节点
		 private
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Trie词频统计可以通过遍历整个Trie来获取每个单词的出现次数,然后可以将这些出现次数存储在一个哈希表中。接着,可以使用排序算法(如快速排序、归并排序等)对这些出现次数进行排序,以获得单词的频率排名。 以下是一个Python实现的示例代码: ```python class TrieNode: def __init__(self): self.children = {} self.freq = 0 class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.freq += 1 def dfs(self, node, word, freq_dict): if node.freq > 0: if word in freq_dict: freq_dict[word] += node.freq else: freq_dict[word] = node.freq for ch in node.children: self.dfs(node.children[ch], word + ch, freq_dict) def get_freq_dict(self): freq_dict = {} self.dfs(self.root, '', freq_dict) return freq_dict def sort_by_freq(words): trie = Trie() for word in words: trie.insert(word) freq_dict = trie.get_freq_dict() sorted_words = sorted(words, key=lambda x: freq_dict[x], reverse=True) return sorted_words ``` 在这个实现中,首先定义了一个Trie,其中节点包含一个字典(用于存储子节点)和一个计数器(用于记录单词出现次数)。然后,将所有单词插入Trie中。接着,使用深度优先搜索(DFS)遍历整个Trie,以获取每个单词的出现次数,并将其存储在一个字典中。最后,使用Python内置的sorted函数对单词进行排序排序方式为按照单词出现次数从大到小排序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值