Sulba
000 / 100

Encode and Decode Strings

MediumTime O(total length) for bothSpace O(total length) for the outputLeetCode 271 ↗

The problem

Design encode, which turns a list of strings into one string, and decode, which turns that string back into the original list.

The strings may contain any characters — including whatever you might have chosen as a separator — so decoding must recover the list exactly.

Examples

01
Input
strs = ["neet", "code", "love", "you"]
Output
["neet", "code", "love", "you"]
02
Input
strs = ["we", "say", ":", "yes"]
Output
["we", "say", ":", "yes"]

Constraints

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

The idea

A plain separator fails as soon as a string contains it. Instead, write each string’s length before it: 4#neet. The decoder reads digits up to the first #, which gives the length n, then takes exactly the next n characters, whatever they are.

Because the decoder never looks for a separator inside a string, a # there is harmless: it is simply one of the n characters taken.

Time
O(total length) for both
Space
O(total length) for the output

Solution · every language run against every case

class Codec:    def encode(self, strs: List[str]) -> str:        # Each string becomes "<length>#<string>", so any character can appear inside it.        return "".join(f"{len(s)}#{s}" for s in strs)     def decode(self, s: str) -> List[str]:        out, i = [], 0        while i < len(s):            j = s.index("#", i)  # the length ends at the first '#'            n = int(s[i:j])            out.append(s[j + 1 : j + 1 + n])            i = j + 1 + n        return out