Trie
Trie (trie) is a multi-tree structure for fast retrieval string. Tire Each node has a plurality of character pointer, while if more scans to insert and retrieve a character string, it is directed towards the characters in the node.
insert
When you need to insert a string, we go from the root, in order to scan each character:
- If the character points to an existing node, the node continue to go down
- If the character point blank, create a new node, move on.
When characters in the string have been retrieved, at which the recording end node.
Retrieval
When you need to retrieve a string if there is, we go from the root, scan each character:
- If the character point blank, then there is no end.
- If the character points to a node, then move on.
When all the characters in the string to be retrieved, if the current node is a node at the end to be labeled, indicating the presence of a string, or its absence explained.
1 int trie[SIZE][26], tot = 1; 2 void insert(char* str){ 3 int len = strlen(str), p = 1; 4 for (int k = 0; k < len; k++){ 5 int ch = str[k] - 'a'; 6 if (trie[p][ch] == 0) trie[p][ch] = ++tot; 7 p = trie[p][ch]; 8 } 9 end[p] = true; 10 } 11 bool search(char* str){ 12 int len = strlen(str), p = 1; 13 for (int k = 0; k <= len; k++){ 14 p = trie[p][str[k] - 'a']; 15 if (p == 0) return false; 16 } 17 return end[p]; 18 }