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 as strs in Machine 1.

Implement the encode and decode 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.

Rust Solution

struct Codec;
use std::iter::FromIterator;

impl Codec {
    fn new() -> Self {
        Codec {}
    }
    fn encode(&self, strs: Vec<String>) -> String {
        let n = strs.len();
        let mut res: String = "".to_string();
        let v = Self::encode_usize(n);
        res.push_str(&v);
        for s in strs {
            let n = s.len();
            let v = Self::encode_usize(n);
            res.push_str(&v);
            res.push_str(&s);
        }
        res
    }

    fn decode(&self, s: String) -> Vec<String> {
        let mut res = vec![];
        let v: Vec<char> = s.chars().collect();
        let n = Self::decode_usize(&v[0..4]);
        let mut index = 4;
        for _ in 0..n {
            let m = Self::decode_usize(&v[index..index + 4]);
            index += 4;
            let ss = String::from_iter(v[index..index + m].iter());
            index += m;
            res.push(ss);
        }
        res
    }

    fn encode_usize(x: usize) -> String {
        let x = x as u32;
        vec![
            (x >> 24 & 0xff) as u8 as char,
            (x >> 16 & 0xff) as u8 as char,
            (x >> 8 & 0xff) as u8 as char,
            (x & 0xff) as u8 as char,
        ]
        .into_iter()
        .collect()
    }

    fn decode_usize(v: &[char]) -> usize {
        ((v[0] as u32) << 24 | (v[1] as u32) << 16 | (v[2] as u32) << 8 | (v[3] as u32)) as usize
    }
}

#[test]
fn test() {
    let obj = Codec::new();
    let strs = vec_string!("123", "321");
    let encoded = obj.encode(strs);
    let decoded = obj.decode(encoded);
    let res = vec_string!("123", "321");
    assert_eq!(decoded, res);
}

Having problems with this solution? Click here to submit an issue on github.