My code:
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 null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strs.size(); i++) {
sb.append(strs.get(i).length() + "/" + strs.get(i));
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> ret = new ArrayList<String>();
if (s == null || s.length() == 0) {
return ret;
}
int i = 0;
int slash = 0;
while (i < s.length()) {
slash = s.indexOf('/', i);
int len = Integer.parseInt(s.substring(i, slash));
ret.add(s.substring(slash + 1, slash + 1 + len));
i = slash + 1 + len;
}
return ret;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
reference:
https://discuss.leetcode.com/topic/22848/ac-java-solution
看的答案,的确巧妙。
前面放长度,后面放string,中间用 ‘/’ 分隔开
本来觉得任何分隔符都会出现,那会造成干扰。其实不会。
比如encode “/”
=> “1//”
decode “1//”
=> “/”
然后,string和前面的范围不能交换。必须先有范围,才能找到后面的string。
Anyway, Good luck, Richardo! — 09/20/2016