forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobzva.cpp
More file actions
57 lines (47 loc) · 1.2 KB
/
obzva.cpp
File metadata and controls
57 lines (47 loc) · 1.2 KB
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
47
48
49
50
51
52
53
54
55
56
57
/**
* For the number of given strings N, and the length of the longest string M,
*
* Encode
* - Time complexity: O(N)
* - Space complexity: O(1)
*
* Decode
* - Time complexity: O(NM)
* - Space complexity: O(M)
*/
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res = "";
for (auto str : strs) {
res += to_string(str.size());
res.push_back('.');
res += str;
}
return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
auto it = s.begin();
while (it != s.end()) {
int str_size = 0;
string tmp = "";
while (*it != '.') {
str_size = str_size * 10 + (*it - '0');
it++;
}
it++;
for (int i = 0; i < str_size; i++) {
tmp.push_back(*it);
it++;
}
res.push_back(tmp);
}
return res;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));