Introduce to Trie
What is Trie
A Trie is a special form of a Nary tree. Typically, a trie is used to store strings. Each Trie node represents a string (a prefix). Each node might have several children nodes while the paths to different children nodes represent different characters. And the strings the child nodes represent will be the origin string represented by the node itself plus the character on the path.
How to represent
Dict
In Python we can use Dictionary to represent it, key is the char and value is the dict. It can save some space but slower because we need to calculate the hashcode every time.
1 | class Trie(object): |
用defalutdict会更加方便
1 | from collections import defaultdict |
Array
We use array can save time but need to create length at least 26 to 256. Key is everytime we need to calculate index ord(char)-97
1 | from collections import defaultdict |
Basic operation
Insert
pseudo-code
1 | 1. Initialize: cur = root |
Search
pseudo-code
1 | 1. Initialize: cur = root |
208 Implement a Trie
1 | from collections import defaultdict |
Question
677. Map Sum Pairs
Using Trie to Srote each char and the count of that
1 | class TrieNode(): |
648. Replace Words
本质思想是构建一个Trie,然后查询的时候如果对应char没有发现,直接返回word,如果查到了prefix 直接返回prefix,都不满足返回word本身
1 | class TrieNode: |
211. Add and Search Word - Data structure design
在基础的Trie上,查询的时候利用DFS,如果当前的char == ‘.’ 那么继续dfs查询之后的一个char,只要有一个满足即可;else则是判断当前char是否在prefix树中
1 | from collections import defaultdict |
212. Word Search II
对于words中的每一个词建立Trie,然后DFS查询在board中能否找到
访问前存储该字母,之后再还原
1 | tmp = board[i][j] |
1 | class Solution(object): |
425. Word Squares
Hard题目,抄了答案,但本质上还是Trie
1 | ''' |