前缀树(Trie树)和Java实现

什么是前缀树

Trie树,即前缀树,又称单词查找树,字典树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。

Trie树的核心思想是空间换时间,利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。 它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

它有3个基本性质:

  • 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  • 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  • 每个节点的所有子节点包含的字符都不相同。

构造前缀树

假设有abc,abd,bcd,efg,hii,那么我们构建如下一个树结构用于表示这些单词:
在这里插入图片描述
但是构造一个前缀树就是为了使遍历那些有相同的前缀的单词时更快速,目前这个多叉树上从根节点到叶节点每一条路径都是一个单词,如果我们增加了单词b,abcd两个单词呢,还是这样一条路走到黑,我们无法区分字母短的单词是否已经存储过,为了解决这个问题,我们可以在节点上记录信息,比如如果到达该字母后单词结尾,我们就在时候的节点上记录end+1,这样就可以知道有几个以该前缀结尾的单词,修改之后结构如下:
在这里插入图片描述
这时我们可以很明显看出来如最左边一条路径上,有一个单词是abc,一个单词是abcd。根据新添加的信息,我们可以知道所有字符串中有多少个该字符串,如果现在有另外一个问题,我想知道所有字符串中有多少个以该字符串作为前缀,那是不是得遍历该条路径后面的节点,将所有的end加起来。为了简单,我们仍然可以在节点中多存入一个信息,每个节点被划过了多少次,也就是在建立多叉树的时候就记录了以所有字符串中有多少个以某字符串作为前缀,划过的次数就是这个值。调整后结构如下:
在这里插入图片描述

代码实现

树节点节点

public static class TrieNode {
	public int path;//记录有几个字符串经过了这个节点,删除用
	public int end;//以该节点结束的字符串的数量,查询用
	public TrieNode[] nexts;//子路径,这里只考虑26个字母

	public TrieNode() {
		path = 0;
		end = 0;
		nexts = new TrieNode[26];
	}
}

前缀树结构

持有一个根节点,具备增删改查的功能

public static class Trie {
	private TrieNode root;

	public Trie() {
		root = new TrieNode();
	}
	
	// 添加字符串
	public void insert(String word) {
	}

	//删除
	public void delete(String word) {
	}

	//查询
	public int search(String word) {
	}
		
	//查询以某字符串为前缀的字符串的数量
	public int prefixNumber(String pre) {
	}
}

插入数据

将字符串按字母分割,从根节点依次追加进前缀树。需要注意如果树中已经存在该节点路径,则复用。

public void insert(String word) {
	if (word == null) {
		return;
	}
	char[] chs = word.toCharArray();
	TrieNode node = root;
	int index = 0;
	for (int i = 0; i < chs.length; i++) {
		index = chs[i] - 'a';
		if (node.nexts[index] == null) {//没有可复用路径,新建节点
			node.nexts[index] = new TrieNode();
		}
		node = node.nexts[index];
		node.path++;//当前节点划过次数加1
	}
	node.end++;//以该节点结束的字符串数量加1
}

查找数据

查找与插入类似,返回最后一个节点的end值

public int search(String word) {
	if (word == null) {
		return 0;
	}
	char[] chs = word.toCharArray();
	TrieNode node = root;
	int index = 0;
	for (int i = 0; i < chs.length; i++) {
		index = chs[i] - 'a';
		if (node.nexts[index] == null) {
			return 0;
		}
		node = node.nexts[index];
	}
	return node.end;
}

删除数据

先类似查找的方式确定是否存在该数据,然后尝试删除。每次删除,其实是将节点的path属性-1。当path属性==0时,从上级节点的nexts列表中remove掉该节点即可return结束。

public void delete(String word) {
	if (search(word) != 0) {
		char[] chs = word.toCharArray();
		TrieNode node = root;
		int index = 0;
		for (int i = 0; i < chs.length; i++) {
			index = chs[i] - 'a';
			if (--node.nexts[index].path == 0) {
				node.nexts[index] = null;
				return;
			}
			node = node.nexts[index];
		}
		node.end--;
	}
}

查询以某字符串为前缀的字符串的数量

public int prefixNumber(String pre) {
	if (pre == null) {
		return 0;
	}
	char[] chs = pre.toCharArray();
	TrieNode node = root;
	int index = 0;
	for (int i = 0; i < chs.length; i++) {
		index = chs[i] - 'a';
		if (node.nexts[index] == null) {
			return 0;
		}
		node = node.nexts[index];
	}
	return node.path;
}

使用Trie树的题目

面试题 17.13. 恢复空格
820. 单词的压缩编码

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Trie字典Java代码实现可以分为以下几部分: 1. 定义Trie节点类,包含children数组和isEndOfWord标识,用于表示是否是单词的结尾。 2. 定义Trie类,包含插入、查找和删除操作。 3. 在Trie类中实现插入操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果不存在则新建节点。 4. 在Trie类中实现查找操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则说明字符串是单词。 5. 在Trie类中实现删除操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则将其设为false,并删除空节点。 如果需要完整代码和注释请告诉我。 ### 回答2: Trie(字典)是一种常用的数据结构,用于高效地存储和查找字符串。下面是Trie字典Java代码实现,用于返回单词。 ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 字母表的大小为26 isEndOfWord = false; } public void insert(String word) { TrieNode curr = this; for (char c : word.toCharArray()) { if (curr.children[c - 'a'] == null) { curr.children[c - 'a'] = new TrieNode(); } curr = curr.children[c - 'a']; } curr.isEndOfWord = true; } public boolean search(String word) { TrieNode node = searchPrefix(word); return node != null && node.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String prefix) { TrieNode curr = this; for (char c : prefix.toCharArray()) { if (curr.children[c - 'a'] == null) { return null; } curr = curr.children[c - 'a']; } return curr; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { root.insert(word); } public boolean search(String word) { return root.search(word); } public boolean startsWith(String prefix) { return root.startsWith(prefix); } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); trie.insert("app"); System.out.println(trie.search("apple")); // 输出:true System.out.println(trie.startsWith("app")); // 输出:true System.out.println(trie.search("banana")); // 输出:false } } ``` 以上代码中,`TrieNode`表示Trie的节点,`Trie`表示Trie的结构。其中`TrieNode`类包含了插入单词、查找单词(完全匹配)以及查找前缀的功能。`Trie`类则是对外提供插入、查找单词和前缀的方法。 在`main`方法中,我们演示了如何使用`Trie`类来插入和查找单词。首先,我们插入了两个单词"apple"和"app"。然后分别调用`search`方法来查找"apple"和"banana",以及`startsWith`方法来查找以"app"开头的单词。最后,打印出对应的结果,即是否找到了对应的单词或前缀。 以上是Trie字典Java代码实现,用于返回单词。 ### 回答3: Trie字典是一种经典的数据结构,用于高效地存储和查找字符串集合。下面是一个基于JavaTrie字典的代码实现,可以实现返回单词的功能: ```java class TrieNode { private final int ALPHABET_SIZE = 26; private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[ALPHABET_SIZE]; isEndOfWord = false; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return current != null && current.isEndOfWord; } public List<String> getAllWords() { List<String> result = new ArrayList<>(); TrieNode current = root; StringBuilder sb = new StringBuilder(); getAllWordsUtil(current, sb, result); return result; } private void getAllWordsUtil(TrieNode node, StringBuilder sb, List<String> result) { if (node == null) { return; } if (node.isEndOfWord) { result.add(sb.toString()); } for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { sb.append((char)('a' + i)); getAllWordsUtil(node.children[i], sb, result); sb.deleteCharAt(sb.length() - 1); } } } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); String[] words = {"hello", "world", "java", "programming"}; for (String word : words) { trie.insert(word); } List<String> allWords = trie.getAllWords(); System.out.println("All words in trie: " + allWords); } } ``` 上述代码中,TrieNode类表示字典的节点,包括一个指向子节点的数组和一个标记,用于表示节点是否是某个单词的结尾。Trie类封装了字典的操作,包括插入单词、查找单词和返回所有单词的功能。在代码的主函数中,我们创建一个Trie对象并插入一些单词,然后调用getAllWords()方法返回字典中的所有单词。最后,打印出返回的单词列表。 希望以上解答对您有所帮助,如有更多疑问,请继续追问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值