题目:
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) { // ... your code return encoded_string; }
Machine 2 (receiver) has the function:
vector<string> decode(string s) { //... your code return strs; }
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2
in Machine 2 should be the same as strs
in Machine 1.
Implement the encode
and decode
methods.
Note:
eval
or serialize methods. You should implement your own encode/decode algorithm.链接: http://leetcode.com/problems/encode-and-decode-strings/
题解:
encode and decode。这里我们可以维护一个StringBuilder,读出每个input string的长度,append一个特殊字符,例如‘/‘,再append string。这样再decode的时候我们就可以利用java的String.indexOf(char,startIndex)来算出自startIndex其第一个‘/‘的位置,同时计算出接下来读取的string长度,用String.substring()读出字符串以后我们更新index,来进行下一次读取。 这些只是简单地encode/decode,至于加密之类的还需要学习Cousera上的Crytography I和II, 作业很难,希望下次开课能坚持下去。
Time Complexity - O(n), Space Complexity - O(1)
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> res = new ArrayList<>(); if(s == null ||s.length() == 0) { return res; } int index = 0; while(index < s.length()) { int forwardSlashIndex = s.indexOf(‘/‘, index); int len = Integer.parseInt(s.substring(index, forwardSlashIndex)); res.add(s.substring(forwardSlashIndex + 1, forwardSlashIndex + 1 + len)); index = forwardSlashIndex + 1 + len; } return res; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(strs));
Reference:
https://leetcode.com/discuss/55020/ac-java-solution
https://leetcode.com/discuss/59840/clean-code-standard-way-of-serialization-deserialization
https://leetcode.com/discuss/57890/1-7-lines-python-length-prefixes
https://leetcode.com/discuss/54906/accepted-simple-c-solution
271. Encode and Decode Strings
原文:http://www.cnblogs.com/yrbbest/p/5027985.html