#C587. Encode and Decode Strings
Encode and Decode Strings
Encode and Decode Strings
You are given a list of strings. Your task is to implement two operations:
- Encode: Convert a list of strings into a single string.
- Decode: Convert the encoded string back into the list of original strings.
The encoding rule is as follows: for each string, first append the length of the string (in decimal), then a colon, and then the string itself. The encoded result is the concatenation of all such encoded strings.
For example, if the input list is \( [\texttt{hello},\texttt{world}] \), the encoded string should be:
\[ 5:hello5:world \]You need to support both encoding and decoding. The input will start with a mode indicator (encode
or decode
). When the mode is encode
, you will be given an integer \( n \) followed by \( n \) strings, and you should output the encoded string. When the mode is decode
, you will be given an encoded string, and you should output the decoded strings each on a separate line.
Note: Strings may contain spaces and special characters. An empty string will be represented as a blank line.
inputFormat
The first line of input contains a command: either encode
or decode
.
- If the command is
encode
: - The second line contains an integer \( n \), the number of strings.
- The next \( n \) lines each contain a string. These strings can be empty or contain spaces.
- If the command is
decode
: - The second line contains the encoded string.
outputFormat
If the command is encode
, output a single line containing the encoded string.
If the command is decode
, output the decoded strings, one per line. If there are no decoded strings, output nothing.
encode
2
hello
world
5:hello5:world