Encode and Decode Strings
Design an algorithm to encode a list of strings to a single string, and decode that single string back to the original list of strings.
Examples
encode(["neet","code","love","you"])
4#neet4#code4#love3#you
Each string is prefixed with its length followed by '#'.
decode("4#neet4#code4#love3#you")["neet","code","love","you"]
Read the length, then read that many characters.
Constraints
- •
1 <= strs.length <= 200 - •
0 <= strs[i].length <= 200 - •
strs[i] contains any possible characters out of 256 valid ASCII characters.
Approaches
Use a special delimiter character that doesn't appear in the strings.
def encode(strs):
return '|'.join(strs)
def decode(s):
if not s:
return []
return s.split('|')Escape the delimiter character within strings.
def encode(strs):
return ''.join(s.replace('|', '||') + '|' for s in strs)
def decode(s):
if not s:
return []
result = []
current = ''
i = 0
while i < len(s):
if s[i] == '|':
if i + 1 < len(s) and s[i+1] == '|':
current += '|'
i += 2
else:
result.append(current)
current = ''
i += 1
else:
current += s[i]
i += 1
return resultEncode each string with its length followed by a '#' delimiter.
Diagram
def encode(strs):
result = ''
for s in strs:
result += str(len(s)) + '#' + s
return result
def decode(s):
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 resultComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Delimiter-Based Encoding | O(n * k) | O(n * k) | Use a special delimiter character that doesn't appear in the strings. |
| Escape Characters | O(n * k) | O(n * k) | Escape the delimiter character within strings. |
| Length-Prefix Encoding | O(n * k) | O(n * k) | Encode each string with its length followed by a '#' delimiter. |
Use a special delimiter character that doesn't appear in the strings.
Escape the delimiter character within strings.
Encode each string with its length followed by a '#' delimiter.
Common Mistakes
Using a simple delimiter without handling it appearing within strings
Not handling empty strings in the input list
Off-by-one errors when parsing the length prefix