题目:

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. JPA学习---第十一节:JPA中的多对多双向关联实体定义与注解设置及操作

    1.定义实体类,代码如下: (1).学生实体类: package learn.jpa.entity; import java.util.HashSet; import java.util.Set; i ...

  2. hibernate 超级牛x的公共类

    想法,能支持in查询和 =查询的 公共方法,类似下面实现 用 泛型 实现 参数 getList(String[] params,Object[] values){} for(int i=0;i< ...

  3. C#开源大全--汇总(转)

    商业协作和项目管理平台-TeamLab 网络视频会议软件-VMukti 驰骋工作流程引擎-ccflow [免费]正则表达式测试工具-Regex-Tester Windows-Phone-7-SDK E ...

  4. Careercup - Microsoft面试题 - 5684901156225024

    2014-05-10 23:45 题目链接 原题: Arrange the numbers in an array in alternating order. For example if the a ...

  5. 6、android 普通日志输出到SD卡

    这是本人见过写博文最负责的一个人: http://www.crifan.com/android_try_use_android_logging_log4j_to_output_log_to_sd_ca ...

  6. PowerDesigner使用技巧

    1.PowerDesigner 批量修改索引或主键对应的表空间 http://blog.sina.com.cn/s/blog_701218960100l0h4.html   2.去掉Oracle生成的 ...

  7. 异步HTTP请求

    一.自定义异步的HTTP请求 1.自定义一个AsyncHttpClient类,用于处理HTTP请求,实际原理就是新开启一个线程,调用HttpClient处理GET和POST请求 package com ...

  8. 【转载】CreateProcess的用法

    第一.第二个参数的用法: 例子: 使用ie打开指定的网页. 注意第二个参数是 可执行文件+命令行参数 #include "stdafx.h" #include <window ...

  9. linux centos yum 安装 rar

    linux yum安装rar时,可能会出现无资源的错误,只需把配置好资源即可,具体操作如下: 1.# vi /etc/yum.repos.d/dag.repo 2.将以下内容写入文件中 [dag] n ...

  10. Tomcat漏洞说明与安全加固

    Tomcat是Apache软件基金会的一个免费的.开放源码的WEB应用服务器,可以运行在Linux和Windows等多个平台上,由于其性能稳定.扩展性好.免费等特点深受广大用户的喜爱.目前,互联网上绝 ...