字典树学习

字典树是一种树形结构,优点是利用字符串的公共前缀来节约存储空间,比如加入“inn int tea ton"之后的字典树,如下:
在这里插入图片描述
字典树的基本性质如下:
根节点没有字符路径。除根节点外,每一个节点都被一个字符路径找到。
从根节点到某一节点,将路径上经过的字符连接起来,为扫过的对应字符串。
每个节点向下所有的字符路径上的字符都不同。

问题如下:

实现字典树结构,包含以下四个主要功能:
void insert(String word):添加word,可重复添加
void delete(String word):删除word,如果word添加过多次,仅删除一个
boolean search(String word):查询word是否在字典树中
int prefinNumber(String pre):返回以字符串pre为前缀的单词数量

public class Main {
	public class TrieNode{
		public int path; //表示有多少个单词公用这个节点
		public int end;//end表示有多少个单词以这个节点结尾
		public TrieNode[] map;
		public TrieNode() {
			path = 0;
			end = 0;
			map = new TrieNode[26];
		}
	}
	public static void main(String[] args) {
		
		
	}
	private TrieNode root;
	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.map[index] == null) {
				node.map[index] = new TrieNode();
			}
			node = node.map[index];
			node.path++;
		}
		node.end ++;
	}
	
	public void delete(String word) {
		if(search(word)) {
			char[] chs = word.toCharArray();
			TrieNode node = root;
			int index = 0;
			for(int i =0;i<chs.length;i++) {
				index = chs[i]- 'a';
				if(node.map[index].path-- ==1) {
					node.map[index] = null;
					return ;
				}
				node = node.map[index];
			}
			node.end --;
		}
	}

	private boolean search(String word) {
		if(word == null) {
			return false;
		}
		char[] chs = word.toCharArray();
		TrieNode node = root;
		int index = 0;
		for(int i = 0;i<chs.length;i++) {
			index = chs[i] -'a';
			if(node.map[index] == null) {
				return false;
			}
			node = node.map[index];
		}
		return node.end!=0;
	}
	
	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.map[index] == null) {
				return 0;
			}
			node = node.map[index];
		}
		return node.path;
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值