leetcode刷题笔记 208题 实现Trie(前缀树)
leetcode刷题笔记 208题 实现Trie(前缀树)
问题描述:
实现一个 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 构成的。
保证所有输入均为非空字符串。
class Trie() {
/** Initialize your data structure here. */
class Node(val children: Array[Node], var isWordEnd: Boolean)
//每个节点包括对应26个字母的位置, 依次将单词拆成字符放入树的每一层
val root = new Node(new Array[Node](26), false)
//逐个字母检查,若为空说明不存在,否则进入对应的下一层的节点
def searchHelper(word: String): Node = {
var ptr = root
for (ch <- word){
if (ptr.children(ch - 'a') == null) return null
ptr = ptr.children(ch - 'a')
}
return ptr
}
/** Inserts a word into the trie. */
//逐层插入,若下层没有节点进行新建
def insert(word: String) {
var ptr = root
for (ch <- word){
if (ptr.children(ch - 'a') == null) ptr.children(ch - 'a') = new Node(new Array[Node](26), false)
ptr = ptr.children(ch - 'a')
}
//对于单词结尾进行标注
ptr.isWordEnd = true
}
/** Returns if the word is in the trie. */
def search(word: String): Boolean = {
val ptr = searchHelper(word)
if (ptr == null) false else ptr.isWordEnd
}
/** Returns if there is any word in the trie that starts with the given prefix. */
def startsWith(prefix: String): Boolean = {
searchHelper(prefix) != null
}
}
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/