Skip to content

Commit c57561a

Browse files
authored
Update 745.Prefix-and-Suffix-Search.cpp
1 parent d585b3b commit c57561a

File tree

1 file changed

+35
-33
lines changed

1 file changed

+35
-33
lines changed

Trie/745.Prefix-and-Suffix-Search/745.Prefix-and-Suffix-Search.cpp

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,62 +2,64 @@ class WordFilter {
22
class TrieNode
33
{
44
public:
5-
TrieNode* next[27];
6-
bool isEnd;
7-
int weight;
5+
bool isEnd;
6+
TrieNode* next[27];
7+
vector<int>ids;
88
TrieNode()
99
{
10+
isEnd = false;
1011
for (int i=0; i<27; i++)
11-
next[i]=NULL;
12-
weight=-1;
12+
next[i] = NULL;
1313
}
14-
};
14+
15+
};
1516
TrieNode* root;
17+
1618
public:
19+
20+
void buildTree(TrieNode* root, string S, int id)
21+
{
22+
TrieNode* node = root;
23+
for (char ch:S)
24+
{
25+
if (node->next[ch-'a']==NULL)
26+
node->next[ch-'a'] = new TrieNode();
27+
node = node->next[ch-'a'];
28+
node->ids.push_back(id);
29+
}
30+
}
31+
1732
WordFilter(vector<string> words)
1833
{
19-
root = new TrieNode();
34+
root = new TrieNode();
2035
for (int i=0; i<words.size(); i++)
2136
{
22-
for (int j=0; j<words[i].size(); j++)
37+
string word = words[i];
38+
string rWord;
39+
for (int j=0; j<word.size(); j++)
2340
{
24-
string suf=words[i].substr(j);
25-
reverse(suf.begin(),suf.end());
26-
insert(root,suf+"{"+words[i],i);
41+
rWord = word.substr(j);
42+
reverse(rWord.begin(),rWord.end());
43+
buildTree(root, rWord+"{"+word,i);
2744
}
28-
insert(root,"{"+words[i],i);
45+
buildTree(root, "{"+word,i);
2946
}
3047
}
3148

3249
int f(string prefix, string suffix)
3350
{
3451
reverse(suffix.begin(),suffix.end());
35-
string s = suffix+"{"+prefix;
36-
52+
string S = suffix+"{"+prefix;
3753
TrieNode* node = root;
38-
for (int i=0; i<s.size(); i++)
54+
for (char ch:S)
3955
{
40-
char ch=s[i];
4156
if (node->next[ch-'a']==NULL)
4257
return -1;
43-
node=node->next[ch-'a'];
44-
}
45-
return node->weight;
46-
}
47-
48-
void insert(TrieNode* root, string word, int weight)
49-
{
50-
TrieNode* node=root;
51-
for (int i=0; i<word.size(); i++)
52-
{
53-
char ch=word[i];
54-
if (node->next[ch-'a']==NULL)
55-
node->next[ch-'a']=new TrieNode();
56-
node=node->next[ch-'a'];
57-
if (node->weight<weight)
58-
node->weight=weight;
58+
else
59+
node = node->next[ch-'a'];
5960
}
60-
}
61+
return node->ids.back();
62+
}
6163
};
6264

6365
/**

0 commit comments

Comments
 (0)