Description:
Write an algorithm to encode a list of strings to a single string, and then decode it back to the original list. Implement both encode and decode functions.
Example 1:
Input: ["learn", "datastructure", "algorithms", "easily"]
Output: ["learn", "datastructure", "algorithms", "easily"]
Example 2:
Input: ["one", "two", "three"]
Output: ["one", "two", "three"]
Example 3:
Input: ["#", "##", "abc#def"]
Output: ["#", "##", "abc#def"]
- Initialize an empty string
encodedStr. - For each string in the input array, append its length, a delimiter (e.g.,
#), and the string itself toencodedStr. - Return the concatenated string.
- Initialize an empty array
decodedStrArrand an index variablei = 0. - While
iis less than the length of the encoded string:- Find the next delimiter (
#) to determine the length prefix. - Parse the length, extract the substring of that length, and add it to the result array.
- Move the index past the extracted substring and repeat.
- Find the next delimiter (
- Return the array of decoded strings.
- Time Complexity: O(n) for both encoding and decoding, where n is the total number of characters in all strings.
- Space Complexity: O(n), for the encoded string and the decoded array.