题目:

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. j2SE基回顾(一)

    1. 九种基本数据类型的大小,以及他们的封装类. 2. Switch能否用string做参数? 3. equals与==的区别. 4. Object有哪些公用方法? Object是所有类的父类,任何类 ...

  2. 玩耍Hibernate之缓存

    2.在持久化层,对象分为哪些状态?分别列出来. 答:瞬时态(Transient).持久态(Persistent).脱管态(Detached). 瞬时态(Transient) 是对象是创建时,瞬时对象在 ...

  3. ubuntu cron.hourly不运行

    服务器没有装NTP,要每天向特定的server进行时间同步,写了一个定时任务,放在/etc/cron.daily下,但是不运行. /etc/crontab文件: # /etc/crontab: sys ...

  4. liferay7中如何Hiding the default Success Message

    下面介绍如何把在Liferay 7中如何把action执行成功之后的信息不显示,因为宝宝有需要,就去查了相关源码和资料. 如果想要某个portlet不显示执行成功的信息,在doProcessActio ...

  5. Asp.net将图片转为Base64编码

    protected void Page_Load(object sender, EventArgs e) { Image img = new Bitmap(Server.MapPath("/ ...

  6. IOS 8 关于 Touch ID

    一.什么是Touch ID? Touch ID是在iPhone 5s后的设备上出现的指纹识别.Apple在IOS 8中开放给第三方APP使用. 可以使用 Touch ID 来验证用户的身份,用户经验证 ...

  7. Matlab动态数组实现

    clear all; clc; a = []; %不是null,也不能什么都不是 for i=1:10 a = [a i]; end

  8. fbx 模型转换 export

    最近在做自定义类型到fbx的转换 有关polygon的理解 vertex,normal,color等信息,是离散的放置的,对fbx里面的mesh加了控制点(vertex)信息之后, 需要再设置poly ...

  9. Maven安装和配置,eclipse创建Maven项目

    提示:使用Maven需要先安装jdk. 下载安装Maven 一.下载最新版的Maven,下载地址:http://maven.apache.org/download.cgi 二.将Maven下载到E:\ ...

  10. discuzx完全自定义设计模板门户首页,栏目,专题模板方法

    第一种:门户首页模板(index.htm,保存于templatedefaultportal) <!--{subtemplate common/header}--> <style id ...