#271
Medium Algorithms Encode and decode strings
Array String Design
51.4% acceptance
Mar 31, 2026
1576
453
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 strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
You are not allowed to solve the problem using any serialize methods (such as eval).
Solution
Rust
Time O(2^n)
Space O(n)
struct Codec {
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Codec {
fn new() -> Self {
Codec {}
}
fn encode(&self, strs: Vec<String>) -> String {
let mut result = String::new();
for s in &strs {
result.push_str(&s.len().to_string());
result.push('#');
result.push_str(s);
}
result
}
fn decode(&self, s: String) -> Vec<String> {
let mut result = Vec::new();
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
let j = s[i..].find('#').unwrap() + i;
let len: usize = s[i..j].parse().unwrap();
result.push(s[j + 1..j + 1 + len].to_string());
i = j + 1 + len;
}
result
}
}
/*
* Your Codec object will be instantiated and called as such:
* let obj = Codec::new();
* let s: String = obj.encode(strs);
* let ans: VecVec<String> = obj.decode(s);
*/