"前缀树(字典树)"
Base.@kwdef mutable struct PrefixTree
isend::Bool = false
children = Dict{Char,PrefixTree}()
end
"给字典树增加单词"
function add_node!(node::PrefixTree, word::String)::Nothing
for c in word
children = node.children
haskey(children, c) || (children[c] = PrefixTree())
node = children[c]
end
node.isend = true
return nothing
end
"在字符串里搜索字典单词"
function search_valid_word(node::PrefixTree, word::String)
res, n = String[], length(word)
for i in 1:n
# 检索 word[i:end]
dict = node
for j in i:n
haskey(dict.children, word[j]) || break # 不存在到该位置的路径
dict = dict.children[word[j]] # 切换到该节点
dict.isend && push!(res, word[i:j])
end
end
res
end
function search_valid_word(node::PrefixTree, word::String)
res, n, word = String[], length(word), collect(word)
for i in 1:n
# 检索 word[i:end]
dict = node
for j in i:n
haskey(dict.children, word[j]) || break # 不存在到该位置的路径
dict = dict.children[word[j]] # 切换到该节点
dict.isend && push!(res, join(word[i:j]))
end
end
res
end
不理解 Julia 字符切片为什么按 unicode 长度算,跟 String 结构有关还是出于什么考虑