271. Encode and Decode Strings
Problem
Design a Codec with encode(strs), which turns a list of strings into one string, and decode(s), which recovers the exact original list. Strings may contain any character, including your delimiter, and may be empty.
Example: decode(encode(["neet","code","love","you"])) → ["neet","code","love","you"]
Any delimiter could appear inside a string, so prefix each string with its length and a separator: "4#neet4#code". To decode, read digits up to #, then take exactly that many characters.
Complexity: O(total length).
class Codec:
def encode(self, strs: List[str]) -> str:
return "".join(f"{len(s)}#{s}" for s in strs)
def decode(self, s: str) -> List[str]:
res, i = [], 0
while i < len(s):
j = s.index("#", i)
n = int(s[i:j])
res.append(s[j + 1:j + 1 + n])
i = j + 1 + n
return res
c = Codec()
for data in (["neet", "code", "love", "you"], ["we", "say", ":", "yes", "#4#", ""], []):
assert c.decode(c.encode(data)) == data
class Codec {
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> res = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int j = s.indexOf('#', i);
int n = Integer.parseInt(s.substring(i, j));
res.add(s.substring(j + 1, j + 1 + n));
i = j + 1 + n;
}
return res;
}
}
type Codec struct{}
func Constructor() Codec {
return Codec{}
}
// Encode writes each string as "<length>#<string>".
func (codec *Codec) Encode(strs []string) string {
var sb strings.Builder
for _, s := range strs {
sb.WriteString(strconv.Itoa(len(s)) + "#" + s)
}
return sb.String()
}
func (codec *Codec) Decode(s string) []string {
res := []string{}
for i := 0; i < len(s); {
j := i + strings.IndexByte(s[i:], '#')
n, _ := strconv.Atoi(s[i:j])
res = append(res, s[j+1:j+1+n])
i = j + 1 + n
}
return res
}