前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Trie - 208. Implement Trie (Prefix Tree)

Trie - 208. Implement Trie (Prefix Tree)

作者头像
ppxai
发布2020-09-23 17:30:29
5140
发布2020-09-23 17:30:29
举报
文章被收录于专栏:皮皮星球皮皮星球

208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Example:

代码语言:javascript
复制
Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

思路:

题目意思很明确,就是实现一下前缀树的几个api,前缀树有用在路由匹配等场景,具体思路都差不多,实现出来之后,可以有很多优化的点,比如插入前缀一个单词等。这里写一下最基本的一个写法,这里使用数组,没有用map来存节点的子节点。

代码:

go:

代码语言:javascript
复制
type Trie struct {

	IsWord bool
	Children [26]*Trie
}


/** Initialize your data structure here. */
func Constructor() Trie {
	return Trie{
		IsWord  : false,
		Children: [26]*Trie{},
	}
}


/** Inserts a word into the trie. */
func (this *Trie) Insert(word string)  {
	cur := this
    for i:=0; i<len(word); i++ {
        c := rune(word[i])
		if cur.Children[c - 'a'] == nil {
			newNode := Constructor()
			cur.Children[c - 'a'] = &newNode
	}
		cur = cur.Children[c - 'a']
	}
	cur.IsWord = true
}


/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
	cur := this
    for i:=0; i<len(word); i++ {
        c := rune(word[i])
		if cur.Children[c - 'a'] == nil {
			return false
		}
		cur = cur.Children[c - 'a']
	}
	return cur.IsWord
}


/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
	cur := this
    for i := 0; i < len(prefix); i++ {
        c := rune(prefix[i])
		if cur.Children[c - 'a'] == nil {
			return false
		}
		cur = cur.Children[c - 'a']
	}
	return true
}


/**
 * Your Trie object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Insert(word);
 * param_2 := obj.Search(word);
 * param_3 := obj.StartsWith(prefix);
 */
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年08月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档