forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlittle_cute_cat_trie.cpp
103 lines (78 loc) · 1.62 KB
/
little_cute_cat_trie.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
93
94
95
96
97
98
99
100
101
102
#include<iostream>
#include<unordered_map>
#include<cstring>
#include<vector>
using namespace std;
//Build a Prefix Tree - Trie
class Node{
public:
char data;
unordered_map<char,Node*> children;
bool isTerminal;
Node(char d){
data = d;
isTerminal = false;
}
};
class Trie{
public:
Node*root;
Trie(){
root = new Node('\0');
}
void insert(string word){
Node* temp = root;
for(char ch : word){
if(temp->children.count(ch)==0){
Node *n = new Node(ch);
temp->children[ch] = n;
}
temp = temp->children[ch];
}
temp->isTerminal = true;
}
};
void searchHelper(Trie t, string document, int i, unordered_map<string,bool> &m ){
Node*temp = t.root;
for(int j = i; j < document.length();j++){
char ch = document[j];
if(temp->children.count(ch)==0){
return;
}
temp = temp->children[ch];
if(temp->isTerminal){
//history part
string out = document.substr(i,j-i+1);
m[out] = true;
}
}
return;
}
void documentSearch(string document, vector<string> words){
//1. Create a trie of words
Trie t;
for(string w : words){
t.insert(w);
}
//2. Searching (Helper Fn)
unordered_map<string,bool> m;
for(int i=0;i<document.length();i++){
searchHelper(t, document, i, m);
}
//3. You can check which words are marked as True inside Hashmap
for(auto w :words){
if(m[w]){
cout<<w <<" : True" <<endl;
}
else{
cout<<w <<" : False "<<endl;
}
}
return;
}
int main(){
string document ="little cute cat loves to code in c++, java & python";
vector<string> words{"cute cat", "ttle", "cat","quick","big"};
documentSearch(document,words);
return 0;
}