-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path271_encode_decode_strings.cpp
42 lines (40 loc) · 1.02 KB
/
271_encode_decode_strings.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
auto init = []() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
return 0;
}();
class Solution {
public:
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
string encode(vector<string> &strs) {
string encoded_ = "";
for (auto& str : strs)
encoded_ += to_string(str.size()) + "#" + str;
return encoded_;
}
/*
* @param str: A string
* @return: decodes a single string to a list of strings
*/
vector<string> decode(string &str) {
vector<string> decoded;
int ptr = 0;
string buffer = "";
int n = str.size();
while (ptr < n) {
if (str[ptr] == '#') {
int length = stoi(buffer);
decoded.push_back(str.substr(ptr + 1, length));
buffer = "";
ptr = ptr + length;
} else
buffer += str[ptr];
++ptr;
}
return decoded;
}
};