271 Encode and Decode Strings
Design an algorithm to encode a list of strings to a 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.
A somewhat trival, but accepted solution
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string encoded = "";
for (string s : strs) {
for (char c : s) {
encoded += c + 1;
}
encoded += ' ';
}
return encoded;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> decoded;
string temp = "";
for (char c : s) {
if (c == ' ') {
decoded.push_back(temp);
temp.clear();
}
else temp += c - 1;
}
return decoded;
}
Congrats on the find
vector<int> encode(string &s, vector<int> &key)
{
if (key.size() < s.length()) {
cout << "invalid key length" << endl;
exit(0);
}
vector<int> encoded;
int iter = 0;
for (char c : s) {
if (iter % 2 == 0)
encoded.push_back((int)c * key[iter++]);
else encoded.push_back((int)c + key[iter++]);
}
return encoded;
}
string decode(vector<int> &encoded, vector<int> &key)
{
string decoded = "";
int iter = 0;
for (int i : encoded) {
if (iter % 2 == 0)
decoded += (char)(i / key[iter++]);
else decoded += (char)(i - key[iter++]);
}
return decoded;
}
string concate_input(int argc, char **argv)
{
string final_con = "";
for (int i = 1; i < argc; i++) {
final_con += argv[i];
}
return final_con;
}
int main(int argc, char **argv)
{
if (argc < 2) {
cout << "expected one or more arguments" << endl;
exit(0);
}
// support 20 characters
vector<int> key = {
42, 282, -264, -287, 12,
280, 145, 192, 274, -56,
-43, -279, -297, 125, 10,
176, 279, -234, -243, -184 };
string msg = concate_input(argc, argv);
cout << msg << endl;
vector<int> encoded = encode(msg, key);
cout << "encoded: ";
for (int i: encoded) cout << i << ' ';
cout << endl;
string decoded = decode(encoded, key);
cout << "decoded: " << decoded << endl;
}
Last updated
Was this helpful?