Skip to content

Commit de1c016

Browse files
committed
Create encode-and-decode-strings.cpp
1 parent 5db6b4a commit de1c016

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

C++/encode-and-decode-strings.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Codec {
5+
public:
6+
7+
// Encodes a list of strings to a single string.
8+
string encode(vector<string>& strs) {
9+
string s;
10+
for (size_t i = 0; i < strs.size(); ++i) {
11+
size_t len = strs[i].length();
12+
string tmp;
13+
for (size_t i = 0, mask = 0xff; i < sizeof(size_t); ++i, mask <<= 8) {
14+
tmp.push_back(len & mask);
15+
}
16+
reverse(tmp.begin(), tmp.end());
17+
s.append(tmp);
18+
s.append(strs[i]);
19+
}
20+
21+
return s;
22+
}
23+
24+
// Decodes a single string to a list of strings.
25+
vector<string> decode(string s) {
26+
vector<string> strs;
27+
size_t pos = 0;
28+
29+
while (pos + sizeof(size_t) <= s.length()) {
30+
size_t len = 0;
31+
for (size_t i = 0; i < sizeof(size_t); ++i) {
32+
len <<= 8;
33+
len += static_cast<unsigned char>(s[pos++]);
34+
}
35+
36+
strs.push_back(s.substr(pos, len));
37+
pos += len;
38+
}
39+
40+
return strs;
41+
}
42+
};

0 commit comments

Comments
 (0)