forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
92 lines (69 loc) · 1.9 KB
/
main2.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/// Source : https://leetcode.com/problems/implement-trie-prefix-tree/description/
/// Author : liuyubobobo
/// Time : 2017-11-05
#include <iostream>
#include <vector>
#include <map>
using namespace std;
/// Trie Non-Recursive version
class Trie{
private:
struct Node{
map<char, int> next;
bool end = false;
};
vector<Node> trie;
public:
Trie(){
trie.clear();
trie.push_back(Node());
}
/** Inserts a word into the trie. */
void insert(const string& word){
int treeID = 0;
for(char c: word){
if(trie[treeID].next.find(c) == trie[treeID].next.end()){
trie[treeID].next[c] = trie.size();
trie.push_back(Node());
}
treeID = trie[treeID].next[c];
}
trie[treeID].end = true;
}
/** Returns if the word is in the trie. */
bool search(const string& word){
int treeID = 0;
for(char c: word){
if(trie[treeID].next.find(c) == trie[treeID].next.end())
return false;
treeID = trie[treeID].next[c];
}
return trie[treeID].end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(const string& prefix) {
int treeID = 0;
for(char c: prefix){
if(trie[treeID].next.find(c) == trie[treeID].next.end())
return false;
treeID = trie[treeID].next[c];
}
return true;
}
};
void printBool(bool res){
cout << (res ? "True" : "False") << endl;
}
int main() {
Trie trie1;
trie1.insert("ab");
printBool(trie1.search("a")); // false
printBool(trie1.startsWith("a")); // true;
cout << endl;
// ---
Trie trie2;
trie2.insert("a");
printBool(trie2.search("a")); // true
printBool(trie2.startsWith("a")); // true;
return 0;
}