1、看完题目感觉想要简单的实现还是很容易的,直接将每次插入的word当作字符串类型存储起来,查找字符串的时候将待查找字符串与存储的各个字符串依次用“==”比较,查找前缀的时候,对存储的各个字符串用strings.HasPrefix库函数查找前缀是否存在。方法十分暴力,但居然通过了,只是执行用时,内存消耗都不太好😭。
代码如下:
type Trie struct {
words []string // 当前字符串word
}
func Constructor() Trie {
return Trie{ words: []string{} }
}
func (this *Trie) Insert(word string) {
this.words=append(this.words, word)
}
func (this *Trie) Search(word string) bool {
for _, v:=range this.words{
if v==word{ return true }
}
return false
}
func (this *Trie) StartsWith(prefix string) bool {
for _, v:=range this.words{
if strings.HasPrefix(v, prefix){ return true }
}
return false
}
2、总感觉这种前面这种解题方法丢掉了这道题本来出题的用意,再加上之前有自己实现过一个简单的前缀树,更感觉不应该是这样的,但一时没想起来可以按单个的字母进行存储,看过题解后恍然大悟,最后实现代码如下:
type Trie struct {
pattern [26]*Trie
isEnd bool
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
node:=this
for _, v:=range word{
t:=v-'a'
if node.pattern[t]==nil{
node.pattern[t]=&Trie{}
}
node=node.pattern[t]
}
node.isEnd=true
}
func (this *Trie) Search(word string) bool {
node:=this.searchPrefix(word)
return node!=nil && node.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
return this.searchPrefix(prefix)!=nil
}
func (this *Trie) searchPrefix(prefix string) *Trie {
node:=this
for _, v:=range prefix{
t:=v-'a'
if node.pattern[t]==nil{ return nil }
node=node.pattern[t]
}
return node
}
还试了一下用不同的初始化方法,但最终的运行评价来看还是在struct中直接初始化的耗时短一点,用make在Constructor进行初始化的代码如下
type Trie struct {
pattern []*Trie
isEnd bool
}
func Constructor() Trie {
return Trie{
pattern: make([]*Trie, 26),
isEnd: false,
}
}
func (this *Trie) Insert(word string) {
node:=this
for _, v:=range word{
t:=v-'a'
if node.pattern[t]==nil{
newNode:=Constructor()
node.pattern[t]=&newNode
}
node=node.pattern[t]
}
node.isEnd=true
}
func (this *Trie) Search(word string) bool {
node:=this.searchPrefix(word)
return node!=nil && node.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
return this.searchPrefix(prefix)!=nil
}
func (this *Trie) searchPrefix(prefix string) *Trie {
node:=this
for _, v:=range prefix{
t:=v-'a'
if node.pattern[t]==nil{ return nil }
node=node.pattern[t]
}
return node
}