字典树/前缀树Trie
自动匹配的程序
数组:[goog, googl, google, bai, baidu, gi]
g
- goog
- googl
- gi
go
- goog
- googl
插入:O(N)
搜索:O(N)
前缀存在:O(NM)(元素个数匹配的时间复杂度)
Trie
root节点 root = Trie()
孩子节点 Hash
结束Flag
对应的值
插入:O(K)
搜索:O(K)
前缀存在:O(K)
词频统计
- 词典中最长的单词
暴力法:
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力扣