forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncode_and_Decode_Strings.cpp
More file actions
33 lines (30 loc) · 902 Bytes
/
Encode_and_Decode_Strings.cpp
File metadata and controls
33 lines (30 loc) · 902 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
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string encodedString;
for(string str: strs) {
encodedString += to_string(str.length()) + '$' + str;
}
return encodedString;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> strs;
size_t n = s.length();
size_t pos = 0;
while(pos < n) {
size_t p = s.find('$', pos);
if(p == string::npos) {
break;
}
size_t len = stoi(s.substr(pos, p - pos));
strs.push_back(s.substr(p + 1, len));
pos = p + 1 + len;
}
return strs;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));