← 返回 nvidia 的题目列表Encode and Decode a List of Strings
类型:online_judge
Problem: Encode and Decode a List of Strings
Given a list of strings strs, implement two methods:
encode(strs) -> str: encodes the list of strings into a single string.
decode(s) -> List[str]: decodes the encoded string back to the original list.
Encoding Rule
Encode each string x and concatenate all encoded pieces:
For each string x, write its length in decimal, followed by the string itself, and then append a delimiter #.
The final encoded string is the concatenation of all pieces in order.
Each piece looks like:
<len><string>#
where <len> is the character length of <string>.
Example
Input:
["foo","lis","jljl","12345678901"]
Encoded output:
3foo#3lis#4jljl#1112345678901#
Explanation: string lengths are 3, 3, 4, and 11.
Constraints / Requirements
strs may be empty.
Strings may contain any visible characters (including #). Your implementation must guarantee decode(encode(strs)) == strs.
Target time complexity: O(total_chars) for both encoding and decoding, where total_chars is the sum of lengths of all strings.
Test Cases (5)
input:
encode\n4\nfoo\nlis\njljl\n12345678901\n
decode\n3foo#3lis#4jljl#1112345678901#\n
output:
["foo", "lis", "jljl", "12345678901"]
["foo", "lis", "jljl", "12345678901"]
input:
encode\n0\n
output:
input:
decode\n\n
output:
[]
input:
encode\n3\na#b\n#\n\n
output:
3a#b#1##0#
input:
decode\n3a#b#1##0#\n
output:
["a#b", "#", ""]
Example
Input
encode
4
foo
lis
jljl
12345678901
decode
3foo#3lis#4jljl#1112345678901#
Output
["foo", "lis", "jljl", "12345678901"]
["foo", "lis", "jljl", "12345678901"]