forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
36 lines (34 loc) · 896 Bytes
/
Solution.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
struct Trie {
Trie* children[26] = {nullptr};
};
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
auto root = new Trie();
for (auto& w : words) {
auto cur = root;
for (int i = w.size() - 1; i >= 0; --i) {
if (cur->children[w[i] - 'a'] == nullptr) {
cur->children[w[i] - 'a'] = new Trie();
}
cur = cur->children[w[i] - 'a'];
}
}
return dfs(root, 1);
}
private:
int dfs(Trie* cur, int l) {
bool isLeaf = true;
int ans = 0;
for (int i = 0; i < 26; ++i) {
if (cur->children[i] != nullptr) {
isLeaf = false;
ans += dfs(cur->children[i], l + 1);
}
}
if (isLeaf) {
ans += l;
}
return ans;
}
};