1
+ /*
2
+ * Created by Xiaozhong on 5/6/2022.
3
+ * Copyright (c) 5/6/2022 Xiaozhong. All rights reserved.
4
+ */
5
+
6
+ #include " iostream"
7
+ #include " vector"
8
+ #include " algorithm"
9
+ #include " string"
10
+ #include " unordered_map"
11
+ #include " unordered_set"
12
+ #include " set"
13
+ #include " map"
14
+ #include " queue"
15
+ #include " functional"
16
+ #include " stack"
17
+
18
+ #define mp make_pair
19
+
20
+ using namespace std ;
21
+
22
+ class Solution {
23
+ struct Node {
24
+ bool isEnd;
25
+ vector<Node *> children;
26
+
27
+ Node () : isEnd(false ), children(vector<Node *>(26 , nullptr )) {}
28
+ };
29
+
30
+ void insert (const string &word) {
31
+ Node *curr = root;
32
+ for (int idx = static_cast <int >(word.size () - 1 ); idx >= 0 ; --idx) {
33
+ char c = word[idx];
34
+ if (curr->children [c - ' a' ] == nullptr ) curr->children [c - ' a' ] = new Node ();
35
+ curr->isEnd = false ;
36
+ curr = curr->children [c - ' a' ];
37
+ }
38
+ curr->isEnd = true ;
39
+ }
40
+
41
+ void dfs (Node *curr, int path) {
42
+ if (curr == nullptr ) return ;
43
+ if (curr->isEnd ) ans += path;
44
+ bool isLeaf = true ;
45
+ for (Node *next: curr->children ) {
46
+ if (next != nullptr ) isLeaf = false ;
47
+ dfs (next, path + 1 );
48
+ }
49
+ if (isLeaf) ans += 1 ;
50
+ }
51
+
52
+ public:
53
+ int minimumLengthEncoding (vector<string> &words) {
54
+ sort (words.begin (), words.end (), [](const string &lhs, const string &rhs) {
55
+ return lhs.size () < rhs.size ();
56
+ });
57
+ for (const string &word: words) insert (word);
58
+ dfs (root, 0 );
59
+ return ans;
60
+ }
61
+
62
+ private:
63
+ int ans = 0 ;
64
+ Node *root = new Node();
65
+ };
66
+
67
+ int main (int argc, char **argv) {
68
+ vector<string> words = {" time" , " me" , " bell" };
69
+ Solution s;
70
+ cout << s.minimumLengthEncoding (words) << endl;
71
+ }
0 commit comments