• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Encode and Decode Strings

 1 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.
 2 
 3 Machine 1 (sender) has the function:
 4 
 5 string encode(vector<string> strs) {
 6   // ... your code
 7   return encoded_string;
 8 }
 9 Machine 2 (receiver) has the function:
10 vector<string> decode(string s) {
11   //... your code
12   return strs;
13 }
14 So Machine 1 does:
15 
16 string encoded_string = encode(strs);
17 and Machine 2 does:
18 
19 vector<string> strs2 = decode(encoded_string);
20 strs2 in Machine 2 should be the same as strs in Machine 1.
21 
22 Implement the encode and decode methods.
23 
24 Note:
25 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.
26 Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
27 Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.

 

If I choose / as spliter, how to ensure the other / wouldn't be seen as spliter? The idea is to store length of the str

This one will be encoded as "6/aa2/bb". When decoding, it finds a string of length of 6 which includes "aa2/bb" so it won't be able to read the "2/" as you might be thinking of.

 1 public class Codec {
 2 
 3     // Encodes a list of strings to a single string.
 4     public String encode(List<String> strs) {
 5         StringBuffer res = new StringBuffer();
 6         for (int i=0; i<strs.size(); i++) {
 7             res.append(strs.get(i).length());
 8             res.append('#');
 9             res.append(strs.get(i));
10         }
11         return res.toString();
12     }
13 
14     // Decodes a single string to a list of strings.
15     public List<String> decode(String s) {
16         List<String> result = new ArrayList<String>();
17         while (s.length() > 0) {
18             int i = s.indexOf("#");
19             int count = Integer.parseInt(s.substring(0, i));
20             result.add(s.substring(i+1, i+1+count));
21             s = s.substring(i+1+count);
22         }
23         return result;
24     }
25 }
26 
27 // Your Codec object will be instantiated and called as such:
28 // Codec codec = new Codec();
29 // codec.decode(codec.encode(strs));

 

posted @ 2015-12-24 12:27  neverlandly  阅读(450)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3