271. Encode and Decode Strings
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Arrays & Hashing
- Time
- O(n)
- Space
- O(n)
Standard Solution (C++)
SummaryImplement a pair of routines that serialize a list of strings into a single string and later reconstruct the original list, handling any characters including separators.
Approach
Use length-prefix encoding so arbitrary characters (including delimiters) are safe.
- For each string, write its length, a delimiter such as '#', then the raw string.
- To decode, read digits up to the '#' to learn the length, then slice exactly that many characters.
class Codec {
public:
string encode(vector<string>& strs) {
string result;
for (const string& s : strs) {
result += to_string(s.size());
result += '#';
result += s;
}
return result;
}
vector<string> decode(string& s) {
vector<string> result;
int i = 0, n = s.size();
while (i < n) {
int j = i;
while (s[j] != '#') j++;
int len = stoi(s.substr(i, j - i));
result.push_back(s.substr(j + 1, len));
i = j + 1 + len;
}
return result;
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground C++
Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.
C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.