Go的数据结构与实现【Trie(前缀树)】

本文详细介绍了Trie(前缀树)数据结构,包括其工作原理、实现方式以及基本操作如插入、搜索、删除和前缀匹配。重点分析了这些操作的时间复杂度。
摘要由CSDN通过智能技术生成

介绍

本文简要介绍了Trie(即前缀树)数据结构,其实现和复杂度分析。

前缀树Trie

trie是一种离散的数据结构,在典型的算法数据结构中并不十分知名或被广泛提及,但仍然是一个重要的结构。
trie(也称为字典树),有时甚至是基数树或前缀树(因为它们可以通过前缀搜索),是一种有序的树结构,它利用了它存储的键,本文假设是字符串。
节点在树中的位置定义了与该节点关联的键,这与二叉搜索树相比有所不同,其中节点存储仅对应于该节点的键。
一个节点的所有后代都有一个与该节点关联的字符串的公共前缀,而根与一个空字符串相关联。
这里我们有一个TrieNode的预览,我们将在我们的Trie实现中使用它:

type TrieNode struct {
   children map[string]*TrieNode
   value    string
   end      bool
}

func NewTrieNode(e string) *TrieNode {
   ret := make(map[string]*TrieNode)
   return &TrieNode{
      children: ret,
      value:    e,
      end:      true,
   }
}

可能存在trie是二叉搜索树的情况,但总的来说,这些情况是不同的。二叉搜索树和前缀树都是树,但是二叉搜索树中的每个节点总是有两个孩子,而前缀树的节点可以有更多。
在trie中,每个节点(根节点除外)都存储一个字符或一个数字。通过从根节点向下遍历trie到特定节点n,可以形成字符或数字的公共前缀,该前缀也由trie的其他分支共享。
通过从叶子节点到根节点遍历树,可以形成一个字符串或一个数字序列。
这是Trie结构体,它表示trie数据结构的实现:

type Trie struct {
   sync.RWMutex
   root *TrieNode
}

func NewTrie() *Trie {
   return &Trie{
      root: &TrieNode{
         children: make(map[string]*TrieNode),
      },
   }
}

常见操作

现在,让我们看看如何实现基本操作。

插入

我们将描述的第一个操作是插入新节点。在我们开始实现之前,了解算法很重要:

  1. 将当前节点设置为根节点
  2. 将当前字母设置为单词的第一个字母
  3. 如果当前节点已经存在对当前字母的引用(通过children字段中的元素之一),则将当前节点设置为该引用节点。否则,创建一个新节点,设置字母等于当前字母,并将当前节点初始化为这个新节点
  4. 重复第3步,直到找到key

该算法的复杂度为O(n),其中n表示key大小。
下面是这个算法的实现:

// Insert a node into trie, the complexity of this operation is O(n),
// where n represents the key size.
func (t *Trie) Insert(word string) {
   t.Lock()
   defer t.Unlock()

   current := t.root

   for i := 0; i < len(word); i++ {
      if child, ok := current.children[string(word[i])]; ok {
         current = child
      } else {
         current.children[string(word[i])] = NewTrieNode(string(word[i]))
         current = current.children[string(word[i])]
      }
   }

   current.end = true
}

搜索
现在让我们添加一个方法来搜索特定元素是否已经存在于trie中:

  1. 获取根的children
  2. 遍历字符串的每个字符
  3. 检查该字符是否已经是子树的一部分。如果它不存在于trie中的任何位置,则停止搜索并返回false
  4. 重复第二步和第三步,直到字符串中没有任何字符。如果到达string的末尾,则返回 true

该算法的复杂度为O(n),其中n表示key的长度。

// Search a node in trie and return true or false, the complexity
// of this algorithm is O(n), where n represents the length of the key.
func (t *Trie) Search(word string) bool {
   t.Lock()
   defer t.Unlock()

   current := t.root

   for i := 0; i < len(word); i++ {
      node := current.children[string(word[i])]
      if node == nil {
         return false
      }
      current = node
   }
   return current.end
}

删除

除了插入和查找元素之外,很明显我们还需要能够删除元素。对于删除过程,我们需要按照以下步骤操作:

检查这个元素是否已经是trie的一部分
如果找到该元素,则将其从trie中删除

该算法的复杂度为O(n),其中n表示key的长度。让我们快速看一下实现:

// Delete a node from trie, the complexity of this algorithm is O(n),
// where n represents the length of the key.
func (t *Trie) Delete(word string) {
   t.Lock()
   defer t.Unlock()

   _ = deleteNode(t.root, word, 0)
}

// deleteNode a node from specific node in trie
func deleteNode(cur *TrieNode, word string, index int) bool {
   if index == len(word) {
      if !cur.end {
         return false
      }
      cur.end = false
      return len(cur.children) == 0
   }

   node := cur.children[string(word[index])]
   if node == nil {
      return false
   }
   shouldDeleteCurrentNode := deleteNode(node, word, index+1) && !node.end

   if shouldDeleteCurrentNode {
      delete(cur.children, string(word[index]))
      return len(cur.children) == 0
   }

   return false
}

前缀匹配

在leetcode.208.实现 Trie (前缀树)中,特别定义了StartsWith方法。如果之前已经插入的字符串word的前缀之一为prefix,返回true;否则,返回false。这只需要在搜索方法基础上改动些许即可,当遍历待匹配的字符串结束后,我们直接返回true。

// StartsWith returns true if there is a previously inserted string word
// that has the prefix, and false otherwise.
func (t *Trie) StartsWith(prefix string) bool {
   current := t.root

   for i := 0; i < len(prefix); i++ {
      node, ok := current.children[string(prefix[i])]
      if !ok {
         return false
      }
      current = node
   }
   return true
}

leetcode.208.实现 Trie (前缀树)题解

这里也给出该题的题解:

type Trie struct {
    root *TrieNode
}

func NewTrieNode(e string) *TrieNode {
    ret := make(map[string]*TrieNode)
    return &TrieNode{
        children: ret,
        value:    e,
        end:      false,
    }
}

type TrieNode struct {
    children map[string]*TrieNode
    value    string
    end      bool
}

func Constructor() Trie {
    return Trie{
        root: &TrieNode{
            children: make(map[string]*TrieNode),
        },
    }
}


func (t *Trie) Insert(word string)  {
    current := t.root

    for i := 0; i < len(word); i++ {
        if current.children == nil {
            current.children = make(map[string]*TrieNode)
        }

        if child, ok := current.children[string(word[i])]; ok {
            current = child
        } else {
            current.children[string(word[i])] = NewTrieNode(string(word[i]))
            current = current.children[string(word[i])]
        }
    }

    current.end = true
}


func (t *Trie) Search(word string) bool {
    current := t.root

    for i := 0; i < len(word); i++ {
        node := current.children[string(word[i])]
        if node == nil {
            return false
        }
        current = node
    }
    return current.end
}


func (t *Trie) StartsWith(word string) bool {
    current := t.root

    for i := 0; i < len(word); i++ {
        node := current.children[string(word[i])]
        if node == nil {
            return false
        }
        current = node
    }
    return true
}
  • 18
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mldxxxxll5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值