forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReplace Words.js
81 lines (71 loc) · 1.95 KB
/
Replace Words.js
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
class Solution {
public:
class trii{
public:
char data;
trii* dict[26];
bool isTerminal;
trii(){
}
trii(char d){
data=d;
for(int i=0;i<26;i++){
dict[i]=NULL;
}
isTerminal=false;
}
};
class tree{
public:
trii* root;
tree(){
root=new trii('\0');
}
void insert(string str,trii* node){
if(str.size()==0){
node->isTerminal=true;
return;
}
int index=str[0]-'a';
if(node->dict[index]==NULL ){
node->dict[index]=new trii(str[0]);
}
insert(str.substr(1),node->dict[index]);
}
string find(string str,trii* node,string pre){
if( node->isTerminal==true ){
return pre;
}
int index=str[0]-'a';
if(str.size()==0 || node->dict[index]==NULL){
return "\0";
}
return find(str.substr(1),node->dict[index],pre+str[0]);
}
string replaceWith(string word ,trii* node){
string temp=find(word,node,"");
if(temp!="\0"){
word=temp;
}
return word;
}
};
string replaceWords(vector<string>& dictionary, string sentence) {
tree* t=new tree();
for(int i=0;i<dictionary.size();i++){
t->insert(dictionary[i],t->root);
}
string ans=sentence;
sentence="";
for(int i=0;i<ans.size();i++){
string word="";
while(i<ans.size()&&ans[i]!=' '){
word+=ans[i];
i++;
}
sentence+=t->replaceWith(word,t->root)+" ";
}
sentence.pop_back();
return sentence;
}
};