Encode and Decode Strings
- 1 min read
- Array
- String
- LC-Easy
- Blind75
Approach
- Add delimiter between strings, i.e. '5#'. This way, we know length of next string and also the delimiter helps us to also encode words that start with numbers.
- If we need to encode '5Hello' and '3World', without # and only number, this would be encoded as '55Hello35World' which would be misinterpreted to mean the first word is 55 characters long.
def encode(.strs: List[str]) -> str:
return ''.join([f'{len(word)}#{word}' for word in strs])
def decode(s: str) -> List[str]:
ans = []
i = 0
while i < len(s):
word_len = ''
while s[i] != '#':
word_len += s[i]
i += 1
word_len = int(word_len)
ans.append(s[i + 1: i + word_len + 1])
i = i + word_len + 1
return ans