271. Encode and Decode Strings

Medium

Problem:

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 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: [""]

https://leetcode.com/problems/encode-and-decode-strings/

Solutions:

If ["aaaa", "bb"] was given as a system design problem, we can represent the strings as "4#aaaa2#bb". The number represents the length of the given string, and the # indicates the start of each string in the list.

System Design

class Codec:
    def encode(self, strs: List[str]) -> str:
        """Encodes a list of strings to a single string.
        """
        res = ""
        for s in strs:
            res += str(len(s)) + "#" + s
        return res

    def decode(self, s: str) -> List[str]:
        """Decodes a single string to a list of strings.
        """
        res, i = [], 0

        while i < len(s):
            j = i

            while s[j] != "#":
                j += 1
            char_length = int(s[i:j])
            res.append(s[j + 1 : j + 1 + char_length])

            i = j + 1 + char_length
        return res


# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))

Last updated