271. Encode and Decode Strings
Description
Design an algorithm to encodea list of stringstoa string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2
in Machine 2 should be the same asstrs
in Machine 1.
Implement theencode
anddecode
methods.
Note:
- The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
- Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
- Do not rely on any library method such as
eval
or serialize methods. You should implement your own encode/decode algorithm.
Note
Think about how data is transferred via socket.
Code
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string rst;
for(auto word:strs) {
//cout << word.size() << ":" << word << endl;
rst += to_string(word.size()) + ":" + word;
}
return rst;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> rst;
int curIndex = 0;
int length = 0;
while(curIndex < s.size()) {
if(true == isdigit(s[curIndex])) {
cout << s[curIndex] << ">" << 10 * length << "+" << (s[curIndex] - '0') << endl;
length = (s[curIndex] - '0') + 10 * length;
cout << endl;
cout << length << endl;
++curIndex;
}
else if(':' == s[curIndex]) {
string tmp = s.substr(++curIndex, length);
//cout << tmp << endl;
rst.push_back(tmp);
curIndex += length;
length = 0;
}
}
return rst;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));