271. Encode and Decode Strings
Referred to this post for why this works:
“aa2/bb” will be encoded as “6/aa2/bb”. When decoding, it finds a string of length of 6 which includes “aa2/bb” so it won’t be able to read the “2/” as you might be thinking of.
Time = O(n), space = O(1)
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String str : strs) {
sb.append(str.length());
sb.append("/");
sb.append(str);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> strs = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int slash = s.indexOf("/", i);
int size = Integer.valueOf(s.substring(i, slash));
i = slash + size + 1;
strs.add(s.substring(slash + 1, i));
}
return strs;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));