【手把手带你刷Leetcode力扣】11.数据结构 - 字典树/前缀树Trie

本文探讨了前缀树(Trie)在字符串匹配问题中的高效解决方案,对比了传统数组方法的效率。通过示例展示了如何使用前缀树进行插入、搜索和前缀检查操作,以及在寻找词典中最长单词的问题上应用前缀树的方法。代码实现包括暴力法和前缀树法,两种方法的时间复杂度分析。视频教程来源于B站—爱学习的饲养员—手把手教你刷Leetcode力扣。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字典树/前缀树Trie

自动匹配的程序
数组:[goog, googl, google, bai, baidu, gi]

g

  • goog
  • googl
  • google
  • gi

go

  • goog
  • googl
  • google

插入:O(N)
搜索:O(N)
前缀存在:O(NM)(元素个数匹配的时间复杂度)

Trie
root节点 root = Trie()
孩子节点 Hash
结束Flag
对应的值

插入:O(K)
搜索:O(K)
前缀存在:O(K)

词频统计

  1. 词典中最长的单词
    暴力法:
class Solution:
	# N is the size of words, M is the size of each word in words
	# Time Complexity: O(sigma(M*N))
	# Space Complexity: O(sigma(M*N))
	def longestWord(self, word: List[str]) -> str:
		if words is None or len(words) == 0:
			return ""
		result = ""
		hashset = set(words)
		for word in words:
			if len(word) > len(result) or (len(word) == len(result) and word < result):
				isWord = True
				l = len(word)
				for i in range(0, l):
					if word[0:i+1] not in hashset:
						isWord = False
						break
				result = word if isWord else result
		return result

前缀树:

class Solution:
	# N is the size of words, M is the size of each word in words
	# Time Complexity: O(sigma(M*N))
	# Space Complexity: O(sigma(M*N))
	def longestWord(self, words: List[str]) -> str:
		if words is None or len(words) == 0:
			return ""
		root = Trie()
		# Insert each word into trie
		for word in words:
			cur = root
			for c in word:
				if c in cur.children:
					cur = cur.children[c]
				else:
					newNode = Trie()
					cur.children[c] = newNode
					cur = newNode
			cul.val = word
			cur.isEnd = True
		# Looking for the eligible word
		result = ""
		for word in words:
			cur = root
			if len(word) > len(result) or (len(word) == len(result) and word < reult):
				isWord = True
				for c in word:
					cur = cur.children[c]
					if not cur.isEnd:
						isWord = False
						break
				result = word if isWord else result
		return result

class Trie:
	def __init__(self):
		self.children = {}
		self.isEnd = False
		self.val = ""

学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值