# 题解：

## 1. 定义类 TrieNode

class TrieNode
{
private boolean isEnd; //该结点是否是一个串的结束
TrieNode next[]; //字母映射表 next

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


# 代码：

public class code208 {

class Trie {

class TrieNode
{
private boolean isEnd; //该结点是否是一个串的结束
TrieNode next[]; //字母映射表 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 node  = root;
char c[] = word.toCharArray();
for(int i = 0; i < c.length; i++)
{
if(node.next[c[i] - 'a'] == null)
{
node.next[c[i] - 'a'] = new TrieNode();
}
node = node.next[c[i] - 'a'];
}
node.isEnd = true;
}

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

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root;
char c[] = prefix.toCharArray();
for(int i = 0; i < c.length; i++)
{
node = node.next[c[i] - 'a'];
if(node == null)
{
return false;
}
}
return true;
}
}

public static void main(String[] args) {
code208 solution = new code208();
Trie trie = solution.new Trie();

trie.insert("apple");
boolean res1 = trie.search("apple");   // 返回 true
boolean res2 = trie.search("app");     // 返回 false
boolean res3 =trie.startsWith("app");  // 返回 true
trie.insert("app");
boolean res4 = trie.search("app");     // 返回 true

System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
System.out.println(res4);
}
}


# 参考：

09-04 63

06-15 151

07-04 33

12-29 31

07-09 37

07-09 55

07-20 240

09-02 136

08-15 1455

09-03 423

#### Trie

©️2020 CSDN 皮肤主题: 点我我会动 设计师: 上身试试

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