Skip to content

Commit 7b5d0ee

Browse files
committed
....
1 parent be8eade commit 7b5d0ee

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

.DS_Store

0 Bytes
Binary file not shown.

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
+ [Rabin Karp Pattern Searching](rabin_karp.cpp)
2929
+ [Z Algorithm](z.cpp)
3030
+ [Finite Automata Pattern Searching](Finite_Automata_Pattern_Searching.cpp)
31-
+ [Trie (Prefix/Radix Tree)](Trie.cpp)
31+
+ [Trie (Prefix/Radix Tree)](algorithms/Trie.cpp)
3232
+ [Longest Common Subsequence](lcs.cpp)
3333
+ [Edit Distance](edit_distance.cpp)
3434
+ [Longest Palindromic Subsequence](lps.cpp)
@@ -101,7 +101,7 @@
101101
+ [Stack](stack.cpp)
102102
+ [Queue](queue.cpp)
103103
+ [List](list.cpp)
104-
+ [Hashtable.cpp](hashtable.cpp)
104+
+ [Hashtable](hashtable.cpp)
105105
+ [HashMap](hashmap.cpp)
106106
+ [HashSet](hashset.cpp)
107107
+ [Union Find(Disjoint Set)](union_find.cpp)

algorithms/Trie.cpp

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
const static int SIZE = 30;
2+
const static int NOT_FOUND = -1;
3+
class trie {
4+
private:
5+
struct trieNode {
6+
int mark;
7+
trieNode* children[SIZE];
8+
trieNode(): mark(NOT_FOUND) {
9+
for(int i = 0; i < SIZE; ++i) {
10+
children[i] = nullptr;
11+
}
12+
}
13+
~trieNode() {
14+
for(int i = 0; i < MAX; ++i) {
15+
delete children[i];
16+
children[i] = nullptr;
17+
}
18+
}
19+
};
20+
trieNode* root;
21+
public:
22+
trie(): root(new trieNode()) {
23+
}
24+
~trie() {
25+
delete root;
26+
root = nullptr;
27+
}
28+
29+
void insert(string const& key, int id) {
30+
trieNode* pCrawl = root;
31+
for(int i = 0; i < key.length(); ++i) {
32+
int indx = key[i] - 'a';
33+
if(!pCrawl->children[indx]) {
34+
pCrawl->children[indx] = new trieNode();
35+
}
36+
pCrawl = pCrawl->children[indx];
37+
}
38+
pCrawl->mark = id;
39+
}
40+
41+
int search(string const& key) {
42+
trieNode *pCrawl = root;
43+
for(int i = 0; i < key.length(); ++i) {
44+
int indx = key[i] - 'a';
45+
if(!pCrawl->children[indx]) {
46+
return NOT_FOUND;
47+
}
48+
pCrawl = pCrawl->children[indx];
49+
}
50+
return pCrawl->mark;
51+
}
52+
};

0 commit comments

Comments
 (0)