271. Encode and Decode Strings
Encode and Decode Strings
Solution
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuffer sb = new StringBuffer();
for (String s : strs) {
sb.append(s.length());
sb.append("/");
sb.append(s);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList<>();
int index = 0;
while (index < s.length()) {
int segmentIndex = s.indexOf("/", index);
int value = Integer.valueOf(s.substring(index, segmentIndex));
String current = s.substring(segmentIndex + 1, value + segmentIndex + 1);
result.add(current);
index = value + segmentIndex + 1;
}
return result;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));Last updated