271. Encode and Decode Strings
271. Encode and Decode Strings
Description
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.
Machine 1 (sender) has the function:
1 | string encode(vector<string> strs) { |
Machine 2 (receiver) has the function:
1 | vector<string> decode(string s) { |
So Machine 1 does:
1 | string encoded_string = encode(strs); |
and Machine 2 does:
1 | vector<string> strs2 = decode(encoded_string); |
strs2
in Machine 2 should be the same as strs
in Machine 1.
Implement the encode
and decode
methods.
You are not allowed tosolve the problem using any serialize methods (such as eval
).
Example 1:
1 | Input: dummy_input = ["Hello","World"] |
Example 2:
1 | Input: dummy_input = [""] |
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
contains any possible characters out of256
valid ASCII characters.
Follow up: Could you write a generalized algorithm to work on any possible set of characters?
Hints/Notes
- 2025/01/04
- string
- premium
Solution
Language: C++
1 | class Codec { |