-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_STOII_0063_replaceWords.cc
128 lines (118 loc) · 2.25 KB
/
Problem_STOII_0063_replaceWords.cc
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// seem as leetcode 0648
// https://leetcode-cn.com/problems/replace-words/
// see at Problem_0648_replaceWords.cc
class Solution
{
class Trie
{
class Node
{
public:
int pass;
int end;
unordered_map<int, Node *> nexts;
Node()
{
pass = 0;
end = 0;
}
};
Node *root;
public:
/** Initialize your data structure here. */
Trie() { root = new Node(); }
/** Inserts a word into the trie. */
void insert(string word)
{
if (search(word))
{
return;
}
Node *cur = root;
cur->pass++;
for (char c : word)
{
if (!cur->nexts.count(c))
{
cur->nexts[c] = new Node();
}
cur = cur->nexts[c];
cur->pass++;
}
cur->end++;
}
/** Returns if the word is in the trie. */
bool search(string word)
{
Node *cur = root;
for (char c : word)
{
if (!cur->nexts.count(c))
{
return false;
}
cur = cur->nexts[c];
}
return cur->end > 0;
}
string getRoot(string word)
{
Node *cur = root;
string x;
for (char c : word)
{
if (!cur->nexts.count(c))
{
return word;
}
cur = cur->nexts[c];
x.push_back(c);
if (cur->end > 0)
{
return x;
}
}
return x;
}
};
public:
vector<string> takeWords(string &sentence)
{
vector<string> words;
int start = 0;
int end = 0;
for (; end < sentence.length(); end++)
{
if (sentence[end] == ' ')
{
words.push_back(sentence.substr(start, end - start));
start = end + 1;
}
}
if (start < sentence.length())
{
words.push_back(sentence.substr(start));
}
return words;
}
string replaceWords(vector<string> &dictionary, string sentence)
{
Trie t;
vector<string> words = takeWords(sentence);
for (auto &word : dictionary)
{
t.insert(word);
}
string ans;
for (auto &word : words)
{
ans += t.getRoot(word) + " ";
}
ans.pop_back();
return ans;
}
};