SDE & MLE Prep

271. Encode and Decode Strings

Problem

Design a Codec with encode(strs), which turns a list of strings into one string, and decode(s), which recovers the exact original list. Strings may contain any character, including your delimiter, and may be empty.

Example: decode(encode(["neet","code","love","you"])) → ["neet","code","love","you"]

Any delimiter could appear inside a string, so prefix each string with its length and a separator: "4#neet4#code". To decode, read digits up to #, then take exactly that many characters.

Complexity: O(total length).

class Codec:
    def encode(self, strs: List[str]) -> str:
        return "".join(f"{len(s)}#{s}" for s in strs)

    def decode(self, s: str) -> List[str]:
        res, i = [], 0
        while i < len(s):
            j = s.index("#", i)
            n = int(s[i:j])
            res.append(s[j + 1:j + 1 + n])
            i = j + 1 + n
        return res