|
| 1 | +class Solution: |
| 2 | + """ |
| 3 | + @param: strs: a list of strings |
| 4 | + @return: encodes a list of strings to a single string. |
| 5 | + """ |
| 6 | + |
| 7 | + # TC : O(n) where n is the combined length of the string in the list of strings. |
| 8 | + # SC : O(S), where S is the sum of the lengths of all strings in strs |
| 9 | + def encode(self, strs): |
| 10 | + res = "" |
| 11 | + for s in strs: |
| 12 | + res += str(len(s)) + ":" + s |
| 13 | + return res |
| 14 | + |
| 15 | + """ |
| 16 | + @param: str: A string |
| 17 | + @return: decodes a single string to a list of strings |
| 18 | + """ |
| 19 | + |
| 20 | + # TC : O(n) where n is the length of encoded string |
| 21 | + # SC : O(S), where S is the total length of the decoded strings. |
| 22 | + def decode(self, str): |
| 23 | + res, i = [], 0 |
| 24 | + |
| 25 | + while i < len(str): |
| 26 | + j = i |
| 27 | + while str[j] != ":": |
| 28 | + j += 1 |
| 29 | + length = int(str[i:j]) |
| 30 | + res.append(str[j + 1 : j + length + 1]) |
| 31 | + i = j + 1 + length |
| 32 | + |
| 33 | + return res |
| 34 | + |
| 35 | + |
| 36 | +def test_solution(): |
| 37 | + solution = Solution() |
| 38 | + |
| 39 | + # Test case 1: Basic test case |
| 40 | + input_strs = ["hello", "world"] |
| 41 | + encoded = solution.encode(input_strs) |
| 42 | + decoded = solution.decode(encoded) |
| 43 | + print(f"Test case 1\nEncoded: {encoded}\nDecoded: {decoded}\n") |
| 44 | + |
| 45 | + # Test case 2: Empty list |
| 46 | + input_strs = [] |
| 47 | + encoded = solution.encode(input_strs) |
| 48 | + decoded = solution.decode(encoded) |
| 49 | + print(f"Test case 2\nEncoded: {encoded}\nDecoded: {decoded}\n") |
| 50 | + |
| 51 | + # Test case 3: List with empty strings |
| 52 | + input_strs = ["", "", ""] |
| 53 | + encoded = solution.encode(input_strs) |
| 54 | + decoded = solution.decode(encoded) |
| 55 | + print(f"Test case 3\nEncoded: {encoded}\nDecoded: {decoded}\n") |
| 56 | + |
| 57 | + # Test case 4: List with mixed empty and non-empty strings |
| 58 | + input_strs = ["abc", "", "def"] |
| 59 | + encoded = solution.encode(input_strs) |
| 60 | + decoded = solution.decode(encoded) |
| 61 | + print(f"Test case 4\nEncoded: {encoded}\nDecoded: {decoded}\n") |
| 62 | + |
| 63 | + # Test case 5: List with special characters |
| 64 | + input_strs = ["he:llo", "wo:rld"] |
| 65 | + encoded = solution.encode(input_strs) |
| 66 | + decoded = solution.decode(encoded) |
| 67 | + print(f"Test case 5\nEncoded: {encoded}\nDecoded: {decoded}\n") |
| 68 | + |
| 69 | + |
| 70 | +test_solution() |
0 commit comments