-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1410.cpp
More file actions
executable file
·77 lines (68 loc) · 1.52 KB
/
LC1410.cpp
File metadata and controls
executable file
·77 lines (68 loc) · 1.52 KB
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
/*
Problem Statement: https://leetcode.com/problems/html-entity-parser/
*/
class TrieNode {
public:
char symbol;
unordered_map<char, TrieNode*> children;
TrieNode() : symbol(0) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() : root(new TrieNode()) {}
void insert(string entity, char symbol) {
TrieNode* node = root;
for (char& c: entity) {
if (!node->children.count(c))
node->children[c] = new TrieNode();
node = node->children[c];
}
node->symbol = symbol;
}
char search(string& text, int l, int r) {
TrieNode* node = root;
for (int i = l; i <= r; i++) {
char& c = text[i];
if (!node->children.count(c))
return 0;
node = node->children[c];
}
return node->symbol;
}
};
class Solution {
public:
string entityParser(string text) {
Trie trie;
int len = 0;
unordered_map<string, char> m = {
{">", '>'},
{"<", '<'},
{"&", '&'},
{""", '\"'},
{"'", '\''},
{"⁄", '/'}
};
// insert entities into the trie with symbol
for (auto& [entity, symbol]: m)
trie.insert(entity, symbol);
// replace occurrences of entity with symbol using trie
for (int i = 0, j = 0; i < text.length(); i++, len++) {
text[len] = text[i];
if (text[i] == '&') // start position of entity
j = len;
else if (text[i] == ';') { // end position of entity
char symbol = trie.search(text, j, len);
if (symbol != 0) { // valid entity
len -= len - j;
text[len] = symbol;
}
j++;
}
}
text.resize(len);
return text;
}
};