#271
Encode and Decode Strings
medium· Arrays & Hashingruns: 0Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings. The implementation must handle any possible characters in the inputs.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 431
class Solution:
def encode(self, strs: list[str]) -> str:
return "".join(f"{len(s)}#{s}" for s in strs)
def decode(self, s: str) -> list[str]:
result = []
i = 0
while i < len(s):
j = i
while s[j] != "#":
j += 1
length = int(s[i:j])
result.append(s[j + 1 : j + 1 + length])
i = j + 1 + length
return result
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.