Problem overview
The class Codec has two methods. encode(_ strs: [String]) -> String turns an array of strings into one string. decode(_ s: String) -> [String] receives only that string, from a different Codec object, and must rebuild the original array in the same order.
The strings can hold any printable ASCII character, including #, digits and spaces, and a string can be empty. For ["lint", "code", "love", "you"], the encoded string is 4#lint4#code4#love3#you, and decoding it gives the same four strings back. For ["3#a", "", "#"] it is 3#3#a0#1##. An empty array encodes to the empty string, and [""] encodes to 0#, so the two stay different.
Approach: write the length first
The obvious plan is to put a separator between the strings and split on it. That fails here, because any character you pick can also appear inside a string. A string such as "#" would be cut in two.
A length prefix avoids the problem. For each string, write its length, a #, and then the string. To decode, read digits up to the next #, convert them to a number length, and take exactly that many characters. Whatever those characters are, they belong to the current string, so the decoder never looks inside it. The next piece starts right after them.
The # after the length matters. Without it, a string that begins with a digit would run into its own length: "12" after a length of 2 would read as 212. Digits contain no #, so the first # from the start of a piece is always the one encode wrote.
Both methods must take O(N) time, where N is the total length of all the strings. That has two consequences. When encoding, append to one growing string rather than rebuilding it. When decoding, move an index through the data rather than cutting the string shorter after every piece.
Step by step
- Start
encodedas an empty string declared withvar, because it grows. - Loop over the strings with
for s in strs. - Append one piece per string: the length as text, then
"#", then the string.s.countis anInt, soString(s.count)converts it. - Return
encodedafter the loop. - In
decode, turnsinto an array of characters. A SwiftStringcan't be read at an integer position, but an array can, in constant time. - Create the result array
strsand an indexithat starts at 0. It marks where the next piece begins. - Loop while
i < chars.count. Each round reads one piece. - Find the
#. Startjatiand advance it whilechars[j]isn't"#". The characters ini..<jare the digits of the length. - Convert the digits to a number.
String(chars[i..<j])builds a string from the slice, andInt(...)parses it into an optional, which!unwraps becauseencodealways wrote valid digits. - Take the string itself: exactly
lengthcharacters after the#, the range(j + 1)..<(j + 1 + length). Append it tostrs. - Move
itoj + 1 + length, the start of the next piece. - Return
strs. For an emptysthe loop never runs and the result is an empty array.
The solution in Swift
class Codec {
func encode(_ strs: [String]) -> String {
var encoded = ""
for s in strs {
encoded += String(s.count) + "#" + s
}
return encoded
}
func decode(_ s: String) -> [String] {
let chars = Array(s)
var strs = [String]()
var i = 0
while i < chars.count {
var j = i
while chars[j] != "#" {
j += 1
}
let length = Int(String(chars[i..<j]))!
strs.append(String(chars[(j + 1)..<(j + 1 + length)]))
i = j + 1 + length
}
return strs
}
}
The Swift details worth a closer look:
Array(s)gives[Character]. Each element is one character as a person sees it, andcounton a string counts characters in the same sense. Becauseencodeanddecodeboth count characters, the lengths agree even if a string holds an accented letter written as two Unicode scalars:"e\u{301}"has count 1, and it round-trips as one character.- Comparing with
"#". Inchars[j] != "#"the literal is read as aCharacter, because that is the element type. - Slices.
chars[i..<j]is anArraySlice<Character>, a view over part of the array.String(...)turns it into a string, copying only those characters. - The
!afterInt(...).Int(String)returnsnilwhen the text isn't a number, and!would then crash. That can't happen for a string made byencode, but decoding arbitrary text this way would not be safe. +=on a string appends in place, so building the result costs time proportional to what is added.
Tracing decode
Here is decode on 3#3#a0#1##, the encoding of ["3#a", "", "#"]. The string has ten characters, at positions 0 to 9.
i | j | length | String taken | New i |
|---|---|---|---|---|
| 0 | 1 | 3 | 3#a | 5 |
| 5 | 6 | 0 | (empty) | 7 |
| 7 | 8 | 1 | # | 10 |
In the first round the inner loop stops at the # in position 1, so the length is 3, and the next three characters, 3#a, form the first string even though they contain a digit and a #. After the third round i is 10, which equals chars.count, so the outer loop ends.
Complexity
Time: O(N). encode appends each string once, and writing a length costs only a few digits. decode copies the string into an array once, and every character is then passed over once: either as part of a length, scanned by the inner loop, or as part of a string, skipped by jumping i forward and copied once into its result string.
Space: O(N) for the encoded string, the character array and the output.
Edge cases and common mistakes
- No strings.
[]encodes to""and decodes to[]. - One empty string.
[""]encodes to0#. The decoder reads length 0, takes zero characters and appends an empty string. - Strings that look like lengths.
["3#a", "", "#"]works because the decoder trusts the length and never inspects the contents. - Dropping the
#. Then["1", "23"]becomes1123, and there is no way to tell where the lengths end. - Cutting
sdown. Rebuilding the remaining string after every piece copies the rest of the data each time, which is quadratic for many strings. The index avoids that.
Testing
["lint", "code", "love", "you"]encodes to4#lint4#code4#love3#youand decodes back unchanged.["3#a", "", "#"]encodes to3#3#a0#1##and decodes back unchanged.[]encodes to the empty string and decodes to[].[""]encodes to0#and decodes to[""].["", ""]encodes to0#0#and decodes to two empty strings.["a b", "12", "#5#"]encodes to3#a b2#123##5#and decodes back unchanged.
