Skip to content

Commit 87004df

Browse files
committed
同步源码
2 parents 7ce21a5 + b9924eb commit 87004df

File tree

3 files changed

+74
-2
lines changed

3 files changed

+74
-2
lines changed

CPP/offer2/CMakeLists.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ add_executable(Offer2_92 Offer2_92.cc)
7373
add_executable(Offer2_90 Offer2_90.cc)
7474
add_executable(Offer2_38 Offer2_38.cc)
7575
add_executable(Offer2_73 Offer2_73.cc)
76+
add_executable(Offer2_65 Offer2_65.cc)
77+
add_executable(Offer2_86 Offer2_86.cc)
7678
add_executable(Offer2_63 Offer2_63.cc)
7779
add_executable(Offer2_62 Offer2_62.cc)
7880
add_executable(Offer2_53 Offer2_53.cc)
@@ -92,4 +94,3 @@ add_executable(Offer2_50 Offer2_50.cc)
9294
add_executable(Offer2_54 Offer2_54.cc)
9395
add_executable(Offer2_64 Offer2_64.cc)
9496
add_executable(Offer2_66 Offer2_66.cc)
95-
add_executable(Offer2_86 Offer2_86.cc)

CPP/offer2/Offer2_65.cc

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
}

CPP/offer2/Offer2_86.cc

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,4 @@ class Solution {
5757
int main() {
5858
Solution s;
5959
s.partition("google");
60-
}
60+
}

0 commit comments

Comments
 (0)