DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)
String Encode and Decode.
In Simple Words:
Encode each string by prepending its length followed by a delimiter (e.g. length#string). On decoding, read until # to parse exact chunk size and slice bytes safely.
- Time: $O(N)$ | Space: $O(1)$ auxiliary
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Allclass Codec:
def encode(self, strs: list[str]) -> str:
res = []
for s in strs:
res.append(f"{len(s)}#{s}")
return "".join(res)
def decode(self, s: str) -> list[str]:
res, i = [], 0
while i < len(s):
j = s.find("#", i)
length = int(s[i:j])
res.append(s[j + 1 : j + 1 + length])
i = j + 1 + length
return res