Skip to content

Commit 6b3f60e

Browse files
committed
Solution: Encode and Decode Strings
1 parent 6f5a4f1 commit 6b3f60e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Let's say sum of lengths of given strings N, and the length of the longest string M
3+
*
4+
* Encode
5+
* - Time complexity: O(N)
6+
* - Space complexity: O(1)
7+
*
8+
* Decode
9+
* - Time complexity: O(N)
10+
* - Space complexity: O(M)
11+
*/
12+
13+
class Codec {
14+
public:
15+
16+
// Encodes a list of strings to a single string.
17+
string encode(vector<string>& strs) {
18+
string res = "";
19+
for (auto str : strs) {
20+
res += to_string(str.size());
21+
res.push_back('.');
22+
res += str;
23+
}
24+
return res;
25+
}
26+
27+
// Decodes a single string to a list of strings.
28+
vector<string> decode(string s) {
29+
vector<string> res;
30+
int str_size = 0;
31+
string tmp = "";
32+
33+
auto it = s.begin();
34+
while (it != s.end()) {
35+
do {
36+
str_size = str_size * 10 + (*it - '0');
37+
it++;
38+
} while (*it != '.');
39+
40+
it++;
41+
42+
for (int i = 0; i < str_size; i++) {
43+
tmp.push_back(*it);
44+
it++;
45+
}
46+
47+
res.push_back(tmp);
48+
str_size = 0;
49+
tmp = "";
50+
}
51+
52+
return res;
53+
}
54+
};
55+
56+
// Your Codec object will be instantiated and called as such:
57+
// Codec codec;
58+
// codec.decode(codec.encode(strs));

0 commit comments

Comments
 (0)