Encode And Decode
Problem statement
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode
and decode
For example:
Input: ["lint","code","love","you"]
Output: ["lint","code","love","you"]
Explanation: One possible encode method is: "lint:;code:;love:;you"
Input: ["we", "say", ":", "yes"]
Output: ["we", "say", ":", "yes"]
Explanation:
One possible encode method is: "we:;say:;:::;yes"
Solution
The idea is to have a separator, lets say #
and a length
of processed word:
For example
["this", "is", "cool##"]
"4#this2#is6#cool##" # decoded
With the number we know exactly what to process.
Similar to second round in: https://www.notion.so/auspham/Amazon-Grad-2021-01e838493e124920a1214d1d8f1bf9c9?pvs=4
import unittest
from typing import *
class App:
DELIMETER = "#"
def encode(self, words: List[str]) -> str:
result = []
for word in words:
result.append("{}#{}".format(len(word), word))
return "".join(result)
def decode(self, encoded: str) -> List[str]:
result = []
i = 0
length = 0
while i < len(encoded):
while (encoded[i] != App.DELIMETER):
length *= 10
length += int(encoded[i])
i += 1
i += 1 # Skip letter #
result.append(encoded[i: i + length])
i += length
length = 0
return result
class AppTest(unittest.TestCase):
def setUp(self):
self.app = App()
return super().setUp()
def test_encode_decode(self):
inputArray = ["we", "say", ":", "yes"]
actual = self.app.decode(self.app.encode(inputArray))
self.assertListEqual(inputArray, actual)
def test_encode_decode_2(self):
inputArray = ["lint","code","love","you"]
actual = self.app.decode(self.app.encode(inputArray))
self.assertListEqual(inputArray, actual)
def test_encode_decode_3(self):
inputArray = []
actual = self.app.decode(self.app.encode(inputArray))
self.assertListEqual(inputArray, actual)
def test_encode_decode_4(self):
inputArray = ["hi"]
actual = self.app.decode(self.app.encode(inputArray))
self.assertListEqual(inputArray, actual)
def test_encode_decode_5(self):
inputArray = ["#", "#", "#"]
actual = self.app.decode(self.app.encode(inputArray))
self.assertListEqual(inputArray, actual)
def test_encode_decode_6(self):
inputArray = ["thisisaverylongwordofcourse", "is", "cool"]
actual = self.app.decode(self.app.encode(inputArray))
self.assertListEqual(inputArray, actual)
if __name__ == "__main__":
unittest.main()