题目:

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 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));

二刷:

这回也写得比较快。

在encode时我们可以对strs先append长度,再append一个delimiter,最后append目标字符串。

在decode时我们从头遍历String s,先保存一个sliding window的左端点lo,遇到delimiter的时候,我们回头去找这个字符串的长度,也就是s.substring(lo, i)。之后我们按照这个长度,把字符串extract出来,并且加入到结果集里,再更新lo以及i。最后返回结果就可以了。

稍快一点的方法可能是在decode时把字符串转换为数组然后处理,但原理大都一致。

Java:

Time Complexity - O(n), Space Complexity - O(n)

public class Codec {

    // Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.length()).append('#').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;
for (int lo = 0, i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '#') {
int len = Integer.parseInt(s.substring(lo, i));
res.add(s.substring(i + 1, i + 1 + len));
lo = i + 1 + len;
i = i + 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的更多相关文章

  1. [LeetCode#271] Encode and Decode Strings

    Problem: Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...

  2. [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 th ...

  3. [LC] 271. Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  4. [LeetCode] Encode and Decode Strings 加码解码字符串

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  5. LeetCode Encode and Decode Strings

    原题链接在这里:https://leetcode.com/problems/encode-and-decode-strings/ 题目: Design an algorithm to encode a ...

  6. Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  7. Encode and Decode Strings 解答

    Question Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...

  8. [Swift]LeetCode271. 加码解码字符串 $ Encode and Decode Strings

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  9. Encode and Decode Strings -- LeetCode

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

随机推荐

  1. net core 实战之 redis 负载均衡和"高可用"实现

    net core 实战之 redis 负载均衡和"高可用"实现 1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的& ...

  2. “我爱淘”冲刺阶段Scrum站立会议3

    完成任务: 将搜索框的界面已经实现以及部署到整个框架中. 计划任务: 实现搜索功能,通过数据库的链接,实现用户可以查到自己需要的书籍的信息. 遇到问题: 1.数据库的操作,怎么实现查询功能: 2.Ac ...

  3. 怎么用PHP发送HTTP请求(转载)

    本文转自:http://blog.snsgou.com/blog/161.html  file_get_contents版本: /** * 发送post请求 * @param string $url ...

  4. 【Binary Tree Level Order Traversal II 】cpp

    题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...

  5. X86架构CPU的逻辑原理

    本篇只是初略介绍X86的逻辑运行原理,并不涉及物理层面和汇编层面的知识. 一.冯洛伊曼体系的运作过程: 1.CPU的历史就不扯了,有兴趣的朋友可以网上搜一下. 2.X86CPU是基于冯洛伊曼架构体系, ...

  6. .NET Framework 4.5、4.5.1 和 4.5.2 中的新增功能

    .NET Framework 4.5.4.5.1 和 4.5.2 中的新增功能 https://msdn.microsoft.com/zh-cn/library/ms171868.aspx

  7. CSS字体选择问题

    在西方国家的字母体系,分成两大字族:serif 及 sans serif.其中 typewriter 打字机字体,虽然也是 sans serif,但由于他是等距字,所以另独立出一个 Typewrite ...

  8. [Bug]没有对“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files”的写访问权限

    问题 环境WIN8.1 x64,新安装的vs与iis,在部署网站时,出现该异常信息.本地机作为测试机,就部署一个站点进行测试,没想到出现这个错误. 解决方案 如果你访问上面的那个路径,你会发现并没有那 ...

  9. 1024: [SCOI2009]生日快乐

    暴力题,N<=10,没注意到平均分,读题真是.. 我们对于一个矩形分成两块进行搜.然后求较大值. ans=min(ans,max(dfs(x,y/n*i,i),dfs(x,y/n*(n-i),n ...

  10. 程序员必须知道的git托管平台

    http://www.open-open.com/lib/view/open1420704561390.html