-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathmain.cpp
51 lines (45 loc) · 1.03 KB
/
main.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
47
48
49
50
51
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string ret;
for (string str : strs) {
ret += to_string(str.length()) + '^' + str;
}
return ret;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> strs;
size_t n = s.length(), p = 0 ;
while (p < n) {
size_t pos = s.find('^', p);
if (pos == string::npos) {
break;
}
size_t sz = stoi(s.substr(p, pos - p));
strs.push_back(s.substr(pos + 1, sz));
p = pos + sz + 1;
}
return strs;
}
};
int main() {
Codec codec;
vector<string> strs = {"hello", "", "a new", "world"};
cout << codec.encode(strs) << endl;
for (string s : codec.decode(codec.encode(strs))) {
cout << s << endl;
}
return 0;
}