Length Prefix Encoding
Intuition
The most robust way to encode strings is to prefix each string with its length followed by a delimiter. For each string, we write the length as a number, then a special character like #, then the string itself. During decoding, we read the length, skip past the #, and extract exactly that many characters. This approach is unambiguous because we always know exactly how many characters to read, regardless of what those characters are.
Algorithm
- **Encode:** For each string, append its length, a `#` delimiter, and the string itself to the result.
- **Decode:** Initialize an index `i` at 0. While `i` is less than the encoded string length:
- Return the decoded list.
O(n) where n is the total number of characters across all stringsSpaceO(n) for the encoded/decoded outputCode (C++ · Java · Python · Go)
class Solution {
public:
string encode(vector<string>& strs) {
string result;
for (const string& s : strs) {
result += to_string(s.size()) + "#" + s;
}
return result;
}
vector<string> decode(string s) {
vector<string> result;
int i = 0;
while (i < s.size()) {
int j = s.find('#', i);
int len = stoi(s.substr(i, j - i));
result.push_back(s.substr(j + 1, len));
i = j + 1 + len;
}
return result;
}
};class Solution {
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.length()).append('#').append(s);
}
return sb.toString();
}
public List<String> decode(String s) {
List<String> result = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int j = s.indexOf('#', i);
int len = Integer.parseInt(s.substring(i, j));
result.add(s.substring(j + 1, j + 1 + len));
i = j + 1 + len;
}
return result;
}
}from typing import List
class Solution:
def encode(self, strs: List[str]) -> str:
result = []
for s in strs:
result.append(str(len(s)) + "#" + s)
return "".join(result)
def decode(self, s: str) -> List[str]:
result = []
i = 0
while i < len(s):
j = s.index("#", i)
length = int(s[i:j])
result.append(s[j + 1:j + 1 + length])
i = j + 1 + length
return resultimport (
"strconv"
"strings"
)
func encode(strs []string) string {
var sb strings.Builder
for _, s := range strs {
sb.WriteString(strconv.Itoa(len(s)))
sb.WriteByte('#')
sb.WriteString(s)
}
return sb.String()
}
func decode(s string) []string {
result := []string{}
i := 0
for i < len(s) {
j := strings.Index(s[i:], "#") + i
length, _ := strconv.Atoi(s[i:j])
result = append(result, s[j+1:j+1+length])
i = j + 1 + length
}
return result
}