KK's blog

每天积累多一些

0%

Trie

算法思路:

Leetcode 208 Implement Trie (Prefix Tree), 也可以用HashMap将所有前缀加入到Map来实现,效率稍低。

注意事项:

  1. TrieNode用{}和is_end,insert, search, startswith用it和i迭代比较
  2. startswith含整个单词,如单词apple,startswith(‘apple’) -> True
  3. Line 11记得加,也就是dict在取value是一定要先检验key是否存在。可以不加,解决方案是用defaultdict(后版本)。

新版本比旧版本更简洁,体现在is_end的处理放在了for循环外。
存储结构举例: a

1
2
3
4
5
6
TrieNode(
children = {
'a': TrieNode(is_End = True)
}
is_end = False
)

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

def __init__(self):
self.head = TrieNode()

def insert(self, word: str) -> None:
it = self.head
for i in range(len(word)):
# if word[i] not in it.children:
#it.children[word[i]] = TrieNode()
it = it.children[word[i]]
it.is_end = True

def search(self, word: str) -> bool:
it = self.head
for i in range(len(word)):
if word[i] not in it.children:
return False
it = it.children[word[i]]
return it.is_end

def startsWith(self, prefix: str) -> bool:
it = self.head
for i in range(len(prefix)):
if prefix[i] not in it.children:
return False
it = it.children[prefix[i]]
return True

class TrieNode:

def __init__(self):
self.children = collections.defaultdict(TrieNode) # {}
self.is_end = False

旧版本: 冗余了一个if语句if i == len(word) - 1

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Trie(TestCases):

def __init__(self):
self.head = TrieNode()

def insert(self, word: str) -> None:
if not word:
return
it = self.head
for i in range(len(word)):
# if word[i] not in it.children:
# it.children[word[i]] = TrieNode()
it = it.children[word[i]]
if i == len(word) - 1:
it.is_end = True

def search(self, word: str) -> bool:
if not word:
return False
it = self.head
for i in range(len(word)):
if word[i] not in it.children:
return False
it = it.children[word[i]]
if i == len(word) - 1 and it.is_end:
return True
return False

def startsWith(self, prefix: str) -> bool:
if not prefix:
return False
it = self.head
for i in range(len(prefix)):
if prefix[i] not in it.children:
return False
it = it.children[prefix[i]]
if i == len(prefix) - 1:
return True
return False

class TrieNode:

def __init__(self):
self.children = collections.defaultdict(TrieNode) # {}
self.is_end = False

算法分析:

每个操作时间复杂度为O(n),空间复杂度O(n),n为单词长度。

Free mock interview