File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(t), t is the number of nodes in trie
3
+
4
+ class Solution {
5
+ public:
6
+ string replaceWords (vector<string>& dict, string sentence) {
7
+ TrieNode trie;
8
+ string result;
9
+ for (const auto & s : dict) {
10
+ trie.Insert (s);
11
+ }
12
+ auto curr = ≜
13
+ for (int i = 0 ; i < sentence.length (); ++i) {
14
+ if (sentence[i] == ' ' || !curr || !curr->isString ) {
15
+ result += sentence[i];
16
+ }
17
+ if (sentence[i] == ' ' ) {
18
+ curr = ≜
19
+ } else if (curr && !curr->isString ) {
20
+ curr = curr->leaves [sentence[i]];
21
+ }
22
+ }
23
+ return result;
24
+ }
25
+
26
+ private:
27
+ struct TrieNode {
28
+ bool isString = false ;
29
+ unordered_map<char , TrieNode *> leaves;
30
+
31
+ void Insert (const string& s) {
32
+ auto * p = this ;
33
+ for (const auto & c : s) {
34
+ if (p->leaves .find (c) == p->leaves .cend ()) {
35
+ p->leaves [c] = new TrieNode;
36
+ }
37
+ p = p->leaves [c];
38
+ }
39
+ p->isString = true ;
40
+ }
41
+
42
+ ~TrieNode () {
43
+ for (auto & kv : leaves) {
44
+ if (kv.second ) {
45
+ delete kv.second ;
46
+ }
47
+ }
48
+ }
49
+ };
50
+ };
You can’t perform that action at this time.
0 commit comments