LeetCode 剑指 Offer II 062. 实现前缀树
题目描述
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。 boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false
LeetCode 剑指 Offer II 062. 实现前缀树
提示:
一、解题关键词
二、解题报告
1.思路分析
2.时间复杂度
3.代码示例
class Trie {
TreeNode root;
class TreeNode{
TreeNode [] next;
boolean isEnd;
TreeNode(){
next = new TreeNode[26];
}
}
/** Initialize your data structure here. */
public Trie() {
root = new TreeNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TreeNode cur = root;
for(char ch : word.toCharArray()){
//判断对应节点是否为空 为空则直接插入
if(cur.next[ch - 'a'] == null){
cur.next[ch - 'a'] = new TreeNode();
}
//继续插入下一个节点
cur = cur.next[ch - 'a'];
}
cur.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TreeNode cur = root;
for(char ch : word.toCharArray()){
//如果对应节点为空 表明不存在这个单词 返回false;
if(cur.next[ch - 'a'] == null){
return false;
}
cur = cur.next[ch - 'a'];
}
return cur.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TreeNode cur = root;
for(char ch : prefix.toCharArray()){
if(cur.next[ch - 'a'] == null){
return false;
}
cur = cur.next[ch - 'a'];
}
return true;
}
}
2.知识点
前缀树 、