Problem Statement

Design an algorithm to encode a list of strings into a single string. The encoded string is then send over the network and is decoded back to the original list of strings.

  • Implement two functions:
    • string encode(vector<string>& strs) – Encodes a list of strings to a single string.
    • vector<string> decode (string s) – Decodes a single string back to the list of strings.

Examples

Example 1:

Input: ["Hello", "World"]
Output: after encode: "0005Hello0005World"
Decoded Output: ["Hello", "World"]

Example 2:

Input: ["leet", "code", "!@#"]
Output: after encode: "0004leet0004code0003!@#"
Decoded Output: ["leet", "code, "!@#"]

Constraints

  • 1 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • Strings strs[i] may contain any of the 256 ASCII characters.

Different Approaches

1️⃣ Delimiter Based Approach

When you encode multiple strings into one, you need a delimiter to separate them.

 

2️⃣ Fixed Size

For the above problem what if the string themselves contain that delimiter.

Example:

Strings: ["abc", "a#b#c"]
If you use '#' as a separator → "abc#a#b#c" 

Now you can't decode uniquely, because you don't know where one ends and the next starts.

To avoid this, we prefix each string with its length.

Code:

 
Buy Me A Coffee

Leave a comment

Your email address will not be published. Required fields are marked *