Encode and Decode Strings Problem
Description
LeetCode Problem 271.
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.
You are not allowed to solve the problem using any serialize methods (such as eval).
Example 1:
Input: dummy_input = ["Hello","World"]
Output: ["Hello","World"]
Explanation:
Machine 1:
Codec encoder = new Codec();
String msg = encoder.encode(strs);
Machine 1 ---msg---> Machine 2
Machine 2:
Codec decoder = new Codec();
String[] strs = decoder.decode(msg);
Example 2:
Input: dummy_input = [""]
Output: [""]
Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]contains any possible characters out of256valid ASCII characters.
Follow up: Could you write a generalized algorithm to work on any possible set of characters?
Solution
Approach: Length Prefix
The obvious idea is to join the strings with a separator such as ,. That breaks as soon as a string contains the separator itself. The strings here can hold any character, so no separator is safe on its own.
Instead, write each string's length in front of it: encode turns every string into <length>#<string> and concatenates them. ["Hello", "World"] becomes 5#Hello5#World.
decode walks the encoded string with an index i:
- Find the first
#at or afteri. Everything betweeniand that#is a number, the lengthsize. - The next
sizecharacters are the string. Take them as they are, then jumpipast them.
The trick is that the decoder never looks inside a string to find where it ends: it already knows the length. So a string like "3#ab" or "#" is copied without confusion, and the empty string encodes as 0#. The # only needs to be unambiguous in the one place we search for it, right after a length, where only digits can come before it.
Complexity: O(n) time for both encode and decode, where n is the total length of all strings. O(n) space for the output.
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
# Each string becomes "<length>#<string>". Its content can be anything, even '#' or digits.
return "".join(str(len(s)) + "#" + s for s in strs)
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings."""
strs = []
i = 0
while i < len(s):
j = s.index("#", i) # the first '#' from i ends the length
size = int(s[i:j])
strs.append(s[j + 1 : j + 1 + size])
i = j + 1 + size # skip the string without looking inside it
return strs