forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
820. Short Encoding of Words.cpp
46 lines (44 loc) · 1.17 KB
/
820. 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
46
class Solution {
private:
struct TrieNode{
int length;
bool isWord;
vector<TrieNode*>next;
TrieNode(int x): length(x), isWord(false), next(vector<TrieNode*>(26)){}
};
TrieNode* root;
public:
int minimumLengthEncoding(vector<string>& words) {
root = new TrieNode(0);
int count = 0;
for(auto& s: words){
reverse(s.begin(), s.end());
buildTrie(s, count);
}
return count;
}
void buildTrie(string& s, int& count){
auto p = root;
bool newWord = false;
for(int i = 0; i < s.size(); i++){
char c = s[i];
if(!p->next[c - 'a']){
if(!newWord){
count++;
if(p->isWord){
count--;
count -= p->length;
p->isWord = false;
}
newWord = true;
}
p->next[c - 'a'] = new TrieNode(i + 1);
}
p = p->next[c - 'a'];
}
if(newWord){
count += p->length;
p->isWord = true;
}
}
};