Encode and Decode Strings
Join a list of strings into one string and get the same list back, whatever characters the strings contain.
Write two methods. encodedecode
Example 1
Output: ["cs", "code", "love", "you"]
Explanation: one possible encoding is "2#cs4#code4#love3#you".
Example 2
Output: ["we", "say", ":", "yes"]
The Idea
Suppose you want to send a list of words to a friend in one text message. The natural thing is to put a comma between them: cs,code,love,you
Now suppose one of the words is itself a,b["a,b"]a,b["a", "b"]:
So how can decode
That is what the encoding in Example 1 does. "cs"2#cs#decode
Look at the picture below. It shows 2#we1##3#yes["we", "#", "yes"]#
Decoding starts at position 0. The group labelled length 2#welength 1#length 3yes
The arcs at the top show the position i
Solution Approach
Turning that idea into code means settling three things: how to write each string, how decode
Writing each string
What exactly goes in front of a string? Its length in ordinary decimal digits, then a ##12ab2ab12#
An empty string still gets a length: ""0#
Finding where a length ends
Why is the first #decode##
Moving to the next string
Where does the next string start? Right after the text just read. If the #hashlenhash + 1hash + lenhash + 1 + len
Java Solution
The methods encodedecode
- In
, create aencode calledStringBuilder . For each stringsb in the list, appends , as.length() and# itself. Returns .sb.toString() - In
, create an empty list,decode , and set the positionresult to 0. Ai loop runs as long aswhile is before the end of the encoded string.i - Inside the loop, find the end of the length with
, the firsts.indexOf('#', i) at or after# , and keep it ini . Turn the digits betweenhash andi into the numberhash withlen .Integer.parseInt - Add the
characters after thelen to# , then setresult toi , the start of the next length.hash + 1 + len - When the loop ends, return
.result
The main#
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EncodeAndDecodeStrings {
// Each string is written as "<length>#<text>", so any character may appear in the text
public static String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.length()).append('#').append(s);
}
return sb.toString();
}
public static List<String> decode(String s) {
List<String> result = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int hash = s.indexOf('#', i); // the length ends at the first '#'
int len = Integer.parseInt(s.substring(i, hash));
result.add(s.substring(hash + 1, hash + 1 + len));
i = hash + 1 + len; // jump straight past the text
}
return result;
}
public static void main(String[] args) {
List<String> a = List.of("cs", "code", "love", "you");
System.out.println(encode(a));
System.out.println(decode(encode(a)));
List<String> b = List.of("we", "say", ":", "yes");
System.out.println(decode(encode(b)));
List<String> c = List.of("we", "#", "yes");
System.out.println(encode(c) + " -> " + decode(encode(c)));
List<String> d = List.of("", "12#ab", "a#b", "");
System.out.println(encode(d) + " -> " + decode(encode(d)).equals(d));
System.out.println("empty list -> \"" + encode(List.of()) + "\" -> "
+ decode(encode(List.of())));
// a plain separator, for comparison: "a#b" and "c" come back as three strings
String joined = String.join("#", List.of("a#b", "c"));
System.out.println(joined + " split on # -> " + Arrays.toString(joined.split("#")));
}
}
Running it prints:
2#cs4#code4#love3#you
[cs, code, love, you]
[we, say, :, yes]
2#we1##3#yes -> [we, #, yes]
0#5#12#ab3#a#b0# -> true
empty list -> "" -> []
a#b#c split on # -> [a, b, c]
2#cs4#code4#love3#you:2#we1##3#yes[we, #, yes]
Look at 0#5#12#ab3#a#b0#12#abdecode5#12#ab0#true""[]
The last line is the comma problem again, with #a#bca#b#c[a, b, c]
The original implementation,
Complexity
Both methods go through the encoded string once, encodedecode#
- Time: O(N) for each method.
appends every character once.encode scans only the digits of each length withdecode , and copies each text once withindexOf , so every character is handled a fixed number of times.substring - Space: O(N). The
inStringBuilder holds the encoded string, and the list fromencode holds the original strings, whose total length is less than N.decode
For another problem that turns strings into a different form and back, see