Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- # Encode and Decode Strings
- 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`
- **Example 1:**
- ```
- Input: ["lint","code","love","you"]
- Output: ["lint","code","love","you"]
- Explanation:
- One possible encode method is: "lint:;code:;love:;you"
- ```
- **Example 2:**
- ```
- Input: ["we", "say", ":", "yes"]
- Output: ["we", "say", ":", "yes"]
- Explanation:
- One possible encode method is: "we:;say:;:::;yes"
- ```
- """
- from typing import List
- class Solution:
- """
- @param: strs: a list of strings
- @return: encodes a list of strings to a single string.
- """
- def encode(self, strs):
- output_string = ""
- for input_string in strs:
- output_string += str(len(input_string)) + ':' + input_string
- return output_string
- """
- @param: str: A string
- @return: decodes a single string to a list of strings
- """
- def decode(self, str):
- output_strings = []
- i = 0
- print(str)
- while i < len(str):
- length = ""
- while str[i] != ':':
- length += str[i]
- i += 1
- length = int(length)
- i += 1 # Skip the ':'
- output_strings.append(str[i:i + length])
- i = i + length
- return output_strings
- def run_tests():
- solution = Solution()
- # First we'll do the test case shown in the task description so that will be the one shown to people first if their code isn't working. If that passes then we'll do other test cases.
- test_cases = [{
- 'input': ["lint", "code", "love", "you"],
- 'output': ["lint", "code", "love", "you"]
- }, {
- 'input': ["we", "say", ":", "yes"]
- }]
- for test_case in test_cases:
- input = test_case['input']
- encoded_string = solution.encode(input)
- if not isinstance(encoded_string, str):
- print(
- 'Test case failed.\nInput: {}\nExpected encode() return type to be str\nGot: {}\n'
- .format(input, type(encoded_string)))
- return
- decoded_string = solution.decode(encoded_string)
- if not decoded_string == input:
- print('Test case decode() failed.\nExpected: {}\nGot: {}\n'.format(
- input, decoded_string))
- return
- print("All test cases passed!")
Advertisement
Add Comment
Please, Sign In to add comment