NOTE

实现Trie前缀树

实现 Trie 前缀树的 LeetCode 解题笔记。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

2. 思路

3. 实现

package main

type node struct {
	m     map[rune]*node
	isEnd bool
}

func newNode() *node {
	return &node{
		m:     make(map[rune]*node, 0),
		isEnd: false}
}

type Trie struct {
	root *node
}

/** Initialize your data structure here. */
func Constructor() Trie {
	return Trie{root: newNode()}
}

/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
	runes := []rune(word)
	current := this.root
	for _, r := range runes {
		n, ok := current.m[r]
		if !ok {
			n = newNode()
			current.m[r] = n
		}
		current = n
	}
	current.isEnd = true
}

/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
	runes := []rune(word)
	current := this.root
	for _, r := range runes {
		current = current.m[r]
		if current == nil {
			return false
		}
	}

	return current.isEnd
}

/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
	runes := []rune(prefix)
	current := this.root
	for _, r := range runes {
		current = current.m[r]
		if current == nil {
			return false
		}
	}

	return current != nil
}

/**
 * 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);
 */

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看