Leetcode 271: Encode and Decode Strings
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:
- The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
- Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
- Do not rely on any library method such as
evalor serialize methods. You should implement your own encode/decode algorithm.
1 public class Codec { 2 3 // Encodes a list of strings to a single string. 4 public string encode(IList<string> strs) { 5 var sb = new StringBuilder(); 6 7 foreach (var s in strs) 8 { 9 sb.Append(s.Length); 10 sb.Append('#'); 11 sb.Append(s); 12 } 13 14 return sb.ToString(); 15 } 16 17 // Decodes a single string to a list of strings. 18 public IList<string> decode(string s) { 19 var result = new List<string>(); 20 if (s == null || s.Length == 0) return result; 21 22 int i = 0, j = 0; 23 24 while (j < s.Length) 25 { 26 if (s[j] != '#') 27 { 28 j++; 29 } 30 else 31 { 32 var len = Int32.Parse(s.Substring(i, j - i)); 33 if (len == 0) 34 { 35 result.Add(""); 36 } 37 else 38 { 39 result.Add(s.Substring(j + 1, len)); 40 } 41 42 j += len + 1; 43 i = j; 44 } 45 } 46 47 return result; 48 } 49 } 50 51 // Your Codec object will be instantiated and called as such: 52 // Codec codec = new Codec(); 53 // codec.decode(codec.encode(strs));

浙公网安备 33010602011771号