Contents
  1. 1. 题目
  2. 2. 解题思路

题目

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 true
trie.search(“app”); // 返回 false
trie.startsWith(“app”); // 返回 true
trie.insert(“app”);
trie.search(“app”); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。

解题思路

开始是root不存储数据
然后引入一个小写字母数组
每个数组里面的对象包含自己和数组还有是否是叶子结点
内部类 TreeNode,包含字符,TreeNode数组,叶子结点标示
每次一个字符,一次遍历查下去
abcde fghij klmno pqrst uvwxy z
字符数组的大小一直错
Trie树的实现
插入没有就新建,有的继续遍历
搜索跟新建相似,最后介绍不是叶子结点就返回false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Trie {
private TreeNode root;
public static class TreeNode{
private char data;
private TreeNode[] child = new TreeNode[26];
private boolean isEndingChar = false;
public TreeNode(char data){
this.data = data;
}
}
/** Initialize your data structure here. */
public Trie() {
root = new TreeNode('/');
}

/** Inserts a word into the trie. */
public void insert(String word) {
TreeNode node = root;
char[] array = word.toCharArray();
for(int i = 0 ; i < array.length ; i++){
int index = array[i] - 'a';
if(node.child[index] == null){
node.child[index] = new TreeNode(array[i]);
}
node = node.child[index];
}
node.isEndingChar = true;
}

/** Returns if the word is in the trie. */
public boolean search(String word) {
TreeNode node = root;
char[] array = word.toCharArray();
for(int i = 0 ; i < array.length ; i++){
int index = array[i] - 'a';
if(node.child[index] == null){
return false;
}
node = node.child[index];
}
if(!node.isEndingChar){
return false;
}
return true;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TreeNode node = root;
char[] array = prefix.toCharArray();
for(int i = 0 ; i < array.length ; i++){
int index = array[i] - 'a';
if(node.child[index] == null){
return false;
}
node = node.child[index];
}
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);
*/
Contents
  1. 1. 题目
  2. 2. 解题思路