Encode and Decode Strings

Length-prefix framing — encode each string as "len#payload"; decode by parsing the length up to the delimiter, then slicing.

Medium
Time O(n) encode and decode Space O(n)
LeetCode
3 min read
string parsing serialization

Problem#

Design encode(list<string>) -> string and decode(string) -> list<string> that round-trip any list of strings.

Examples#

  • ["lint","code","love","you"]"4#lint4#code4#love3#you"["lint","code","love","you"].
  • [""]"0#"[""].

Constraints#

  • Strings may contain any 256 byte values; 1 <= strs.length <= 200, sum of lengths <= 200.

Approach#

Length-prefix each string with its byte count followed by #. Decoding parses digits until #, reads that many bytes as the payload, repeats.

Solution#

Encode and Decode Strings
class Codec {
public:
string encode(vector<string>& strs) {
string out;
for (auto& s : strs) {
out += to_string(s.size());
out += '#';
out += s;
}
return out;
}
vector<string> decode(string s) {
vector<string> out;
int i = 0, n = s.size();
while (i < n) {
int j = s.find('#', i);
int len = stoi(s.substr(i, j - i));
out.push_back(s.substr(j + 1, len));
i = j + 1 + len;
}
return out;
}
};

Editorial#

A length prefix is byte-safe — no escape sequences needed, the delimiter only appears immediately after the digits. Any naive delimiter-only scheme breaks when the data itself contains the delimiter.

Complexity#

  • Time: O(n) for both.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.