Trie

本文深入探讨了Trie数据结构,一种高效用于字符串搜索的树形结构。Trie树的时间复杂度仅与查询字符串长度相关,而非数据量大小,显著提高了搜索效率。文章详细介绍了Trie树的节点构成、实现原理及添加、查询操作,并通过代码示例展示了其工作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Trie:Trie这种数据结构主要应用在搜索字符串上。比如要想查询一个字符串是否存在数组中。可以用到的集合可以是TreeMap,TreeMap这种数据结构的特点是就算是最好的满二叉树,达到的时间复杂度也会是O(logn)。而Trie是这样一种数据结构,它的时间复杂度可以与要存入的数据量无关,只与要查询的字符串的长度有关。举例来说,这种数据结构的节点可以只包括两个变量{isWorld 和 next}。next是个TreeMap结构的数据结构<Charcter,Node>。key为一个字符,而value为下一个Node的地址。这样就可以将一个字符串连接起来。所以,搜索的时候可以只搜索到字符串的长度就可以了。而这种数据结构所带来的不好的就是会造成很大的空间的浪费。

public class Trie {
	
	//首先创建节点
	private class Node{
		
		//代表是否是单词的标志
		public boolean isWorld;
		//代表是否出现过这个字母,以及这个字母后面所指向的另一个节点的位置。
		public TreeMap<Character,Node> next;
		
		public Node(boolean isWorld) {
			this.isWorld = isWorld;
			next = new TreeMap<>();
		}
		public Node() {
			this(false);
		}
	
	}
	
	
	//创建属于这个类的变量,首先是根节点
	public Node root;
	//创建一个变量,记录有多少个单词
	public int size;
	
	
	//创建构造函数,不需要传参数,因为只需要创建一颗trie
	public Trie() {
		root = new Node();
		size = 0;
	}
	
	//创建一个获取存了多少单词的方法
	public int getSize() {
		return size;
	}
	
	//创建一个添加单词的方法
	public void add(String str) {
		Node cur = root;
		for(int i = 0;i<str.length();i++) {
			char c = str.charAt(i);
			if(cur.next.get(c) == null) {
				cur.next.put(c, new Node());
			}
			cur = cur.next.get(c);
		}
		if(cur.isWorld == false) {
			cur.isWorld = true;
			size++;
		}
	}
	
	//查询某个单词是否存在其中
	public boolean contains(String str) {
		Node cur = root;
		for(int i = 0;i<str.length();i++) {
			char c = str.charAt(i);
			if(cur.next.get(c)==null) {
				return false;
			}
			cur = cur.next.get(c);
		}
		
		return cur.isWorld;
	}
	
	//带有通配符的查询
	public boolean search(String str) {
		return match(root,str,0);
	}
	private boolean match(Node root,String str,int index) {
		if(index == str.length()) {
			return root.isWorld;
		}
		char c = str.charAt(index);
		if(c !='.') {
			if(root.next.get(c) == null)
				return false;
			return match(root.next.get(c),str,index+1);
		}
		else {
			for(char key:root.next.keySet()) {
				if(match(root.next.get(key),str,index+1)) {
					return true;
				}
			}
			return false;
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值