Array & Hashing
57. Encode and Decode String
Design an algorithm to encode a list of strings into a single string and decode it back to the original list of strings.
The encoded string is sent over the network and later decoded back to the original list.
Requirements
- The strings may contain any of the 256 valid ASCII characters.
- Your algorithm must correctly handle all possible characters, including special symbols such as
:,;, etc. - Do not rely on libraries -- the goal is to implement the encoding and decoding logic manually.
Examples
Example 1
Input: ["lint","code","love","you"]
Output: ["lint","code","love","you"]
Explanation: One possible encoding method: "lint:;code:;love:;you"
Example 2
Input: ["we", "say", ":", "yes"]
Output: ["we", "say", ":", "yes"]
Explanation: One possible encoding method: "we:;say:;:::;yes"
from typing import List
def encode(strs: List[str]) -> str:
res: str = ""
for word in strs:
res += str(len(word)) + "#" + word
return res
def decode(strg: str) -> List[str]:
res: List[str] = []
i: int = 0
while i < len(strg):
j = i
# Find the '#' delimiter
while strg[j] != "#":
j += 1
# Get the length of the next word
length: int = int(strg[i:j])
# Extract the word
res.append(strg[j + 1 : j + 1 + length])
# Advance the pointer past the current word
i = j + 1 + length
return res Keyboard shortcuts
← h Previous problem
→ l Next problem
Esc Back to index
? Toggle this help