Problem 271: Encode and Decode Strings
思路
复杂度
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
if (strs == null || strs.size() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String s : strs) {
int len = s.length();
sb.append(len);
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> rst = new ArrayList<>();
if (s == null || s.length() == 0) {
return rst;
}
int index = 0;
while (index < s.length()) {
int slashIndex = s.indexOf("/", index);
int len = Integer.parseInt(s.substring(index, slashIndex));
rst.add(s.substring(slashIndex + 1, slashIndex + 1 + len));
index = slashIndex + 1 + len;
}
return rst;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));易错点
Last updated

