一、例题
题目都已经明目张胆的提醒我们使用Trie树了,然而我并不会,暴力法失败。。。直接看题解
二、Trie树
Trie树是一种变种多叉树。
普通的多叉树的数据结构:
class MTreeNode {
Type val;
MTreeNode[] nexts;
}
// nexts表示下一层级树的节点集合,通过数组的每个位置的指针指向每个下一层的节点。
Trie树的数据结构:
class TrieNode {
boolean isEnd; //标记当前字符是不是一个单词的末尾
TrieNode[] nexts; //记录下一层节点位置, 长度恒为26
}
对于小写字母的Trie树,且nexts数组恒为26,即一一对应26个字母;
isEnd是这条路径上所有单词的末尾节点都为true【如sea,seane其中a和e都是Ture】
每个单词是否存在某个字符,是通过这个单词路径上对应位置是否为null确定的
若将一个单词看做一个由字母表示的链表,那么每个字符就是一个链表节点;又因为nexts是一个节点数组,可以想象到,Trie树的结构是这样的:
[注:最后一个节点为空节点,为什么会有空节点,我也不知道,看代码应该不会存在啊?]
属性及方法定义
- 属性、构造方法:
private boolean isEnd;
private Trie[] nexts;
/** Initialize your data structure here. */
public Trie() {
nexts = new Trie[26];
isEnd = false; //默认为false,可以不写
}
- 插入方法:
/** Inserts a word into the trie. */
public void insert(String word) {
Trie cur = this;
for (char c: word.toCharArray()) {
if (cur.nexts[c - 'a'] == null) {
//为空时才创建节点,防止重复创建
cur.nexts[c - 'a'] = new Trie();//在这里的时候,下一层节点的数组就已经被初始化了
}
cur = cur.nexts[c - 'a'];
}
cur.isEnd = true;
}
- 查询单词的方法:
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie cur = this;
for (char c : word.toCharArray()) {
//路径上没有这个字符,说明这个单词不存在
if (cur.nexts[c - 'a'] == null) return false;
cur = cur.nexts[c - 'a'];
}
//因为是完整的单词,因此需要为true
return cur.isEnd;
}
- 查询前缀是否存在的方法【总体上和search()相同,但是不需要保证是一个单词】
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie cur = this;
for (char c : prefix.toCharArray()) {
//和search同样的道理
if (cur.nexts[c - 'a'] == null) return false;
cur = cur.nexts[c - 'a'];
}
return true; //只是查询一个前缀,不能保证这个前缀是一个实际的单词,如测试用例中的app刚开始就不是存在的
}
本文参考至路漫漫我不畏的题解