[LeetCode]208. 实现 Trie (前缀树)(java实现)

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 读题(需要重点注意的东西)

3. 解法

详细的构建思路,请看下文 5. 所用到的数据结构与算法思想


class Trie {

	private class TrieNode {
		private boolean isEnd;
		private TrieNode[] next;

		public TrieNode() {
			isEnd = false;
			next = new TrieNode[26];
		}

	}

	private TrieNode root;

	/** Initialize your data structure here. */
	public Trie() {
		root = new TrieNode();
	}

	/** Inserts a word into the trie. */
	public void insert(String word) {
		TrieNode cur = root;
		for (int i = 0, len = word.length(), ch; i < len; i++) {
			ch = word.charAt(i) - 'a';
			if (cur.next[ch] == null)
				cur.next[ch] = new TrieNode();
			cur = cur.next[ch];
		}
		cur.isEnd = true;
	}

	/** Returns if the word is in the trie. */
	public boolean search(String word) {
		TrieNode cur = root;
		for (int i = 0, len = word.length(), ch; i < len; i++) {
			ch = word.charAt(i) - 'a';
			if (cur.next[ch] == null)
				return false;
			cur = cur.next[ch];
		}
		return cur.isEnd;
	}

	/**
	 * Returns if there is any word in the trie that starts with the given prefix.
	 */
	public boolean startsWith(String prefix) {
		TrieNode cur = root;
		for (int i = 0, len = prefix.length(), ch; i < len; i++) {
			ch = prefix.charAt(i) - 'a';
			if (cur.next[ch] == null)
				return false;
			cur = cur.next[ch];
		}
		return true;
	}
}
/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

4. 可能有帮助的前置习题

5. 所用到的数据结构与算法思想

6. 总结

这是前缀树相关问题的基础,一般题目是不会给出前缀树的相关定义代码的,如果在解题中要利用前缀树,就必须自己在解题时定义。
如果无法实现,请看Java数据结构—Trie(字典树/前缀树)一篇弄懂前缀树!图解、完整注释!,并将代码熟记直至能够完整默写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cloudeeeee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值