Encode and Decode Strings
Encode and Decode Strings
String
Problem Statement
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.
Example
Example 1:
Input: ["lint","code","love","you"]
Input: ["lint","code","love","you"]
Encoded: "4#lint4#code4#love3#you"
Output: ["lint","code","love","you"]
Solution (Length-prefixed)
A robust way to encode a list of strings is to prefix each string with its length, followed by a delimiter. This allows us to know exactly how many characters to read for each string during decoding, even if the strings themselves contain the delimiter.
Algorithm Steps
- Encode: For each string, prepend its length and a delimiter (e.g., '#'). Concatenate all these new strings together.
- Decode: Iterate through the encoded string. At each step, find the delimiter to determine the length of the next string. Read that many characters to get the original string. Repeat until the end of the encoded string is reached.
Input: ["lint","code","love","you"]
Encoded:
Start encoding.
Encode and Decode Strings Solution