codekofi
← All problems

Problem 107

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1string pack(const vector<string>& items) {
2
3 string out;
4
5 for (const string& s : items) {
6 out += to_string(s.size());
7 out += ':';
8 out += s;
9 }
10
11 return out;
12}
13
14vector<string> unpack(const string& data) {
15
16 vector<string> out;
17
18 int i = 0;
19 int n = data.size();
20
21 while (i < n) {
22
23 int j = i;
24
25 while (data[j] != ':') {
26 j++;
27 }
28
29 int len = stoi(data.substr(i, j - i));
30
31 out.push_back(data.substr(j + 1, len));
32
33 i = j + 1 + len;
34 }
35
36 return out;
37}
38
39pair<string, vector<string>> solution(const vector<string>& items) {
40
41 string data = pack(items);
42
43 return {data, unpack(data)};
44}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.