forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
short-encoding-of-words.cpp
45 lines (41 loc) · 1.23 KB
/
short-encoding-of-words.cpp
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
// Time: O(n), n is the total sum of the lengths of words
// Space: O(t), t is the number of nodes in trie
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
unordered_set<string> unique_words(words.cbegin(), words.cend());
vector<TrieNode *> leaves;
TrieNode trie;
for (auto word : unique_words) {
reverse(word.begin(), word.end());
leaves.emplace_back(trie.Insert(word));
}
int result = 0;
int i = 0;
for (const auto& word: unique_words) {
if (leaves[i++]->leaves.empty()) {
result += word.length() + 1;
}
}
return result;
}
private:
struct TrieNode {
unordered_map<int, TrieNode *> leaves;
TrieNode *Insert(const string& s) {
auto* p = this;
for (const auto& c : s) {
if (!p->leaves[c - 'a']) {
p->leaves[c - 'a'] = new TrieNode;
}
p = p->leaves[c - 'a'];
}
return p;
}
~TrieNode() {
for (auto& node : leaves) {
delete node.second;
}
}
};
};