forked from 1AvneetKaur/hacktoberfest2022-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencodeAndDecodeStrings.cpp
More file actions
35 lines (29 loc) · 844 Bytes
/
encodeAndDecodeStrings.cpp
File metadata and controls
35 lines (29 loc) · 844 Bytes
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
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string result = "";
for (int i = 0; i < strs.size(); i++) {
string str = strs[i];
result += to_string(str.size()) + "#" + str;
}
return result;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> result;
int i = 0;
while (i < s.size()) {
int j = i;
while (s[j] != '#') {
j++;
}
int length = stoi(s.substr(i, j - i));
string str = s.substr(j + 1, length);
result.push_back(str);
i = j + 1 + length;
}
return result;
}
private:
};