Encode and Decode Strings

要点:题的特点:不是压缩,而是encode为字节流。所以需要找delimiter来分割每个word,但是delimiter可能是字符本身,所以可以用数字记录每个word的长度。这样一般比delimiter简单并且节省空间。接着可能会想到如果前后单词有数字怎么办?所以需要一个特殊字符来分割数字和词本身,而这个字符要在数字之后:不用担心前面单词以数字结尾,前一个单词通过长度信息已经成功decode。

  • ''.join('%d:' % len(s)+s for s in strs)意思:(‘%d:’% len(s) + s) 这个对strs做list comprehension产生新list,所以每个都有len(s):在开头,new style是’’.join(‘{}:{}’.format(len(s), s) for s in strs

错误点:

  • 要用find(‘:’, i),也就是有boundary的方法来得到下一个:的位置
  • 这题证明list.append => join 比str+=快不少
  • 实际上,多string/int混合最好用formatter

https://repl.it/Cgvz/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.

# 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.
# Hide Company Tags Google
# Hide Tags String
# Hide Similar Problems (E) Count and Say (H) Serialize and Deserialize Binary Tree class Codec: def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str]
:rtype: str
"""
return ''.join("%d:" % len(s) + s for s in strs) def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str
:rtype: List[str]
"""
i = 0
ret = []
while i<len(s):
j = s.find(':', i) # error 1: should have i as find's left boundary, inclusive
i = j+int(s[i:j])+1
ret.append(s[j+1:i]) return ret sol = Codec()
assert sol.decode(sol.encode(['3e5d', 'd:4rf']))==['3e5d', 'd:4rf']

边工作边刷题:70天一遍leetcode: day 81的更多相关文章

  1. 边工作边刷题:70天一遍leetcode: day 89

    Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...

  2. 边工作边刷题:70天一遍leetcode: day 77

    Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...

  3. 边工作边刷题:70天一遍leetcode: day 78

    Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...

  4. 边工作边刷题:70天一遍leetcode: day 85-3

    Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...

  5. 边工作边刷题:70天一遍leetcode: day 101

    dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...

  6. 边工作边刷题:70天一遍leetcode: day 1

    (今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...

  7. 边工作边刷题:70天一遍leetcode: day 70

    Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...

  8. 边工作边刷题:70天一遍leetcode: day 71-3

    Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...

  9. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

随机推荐

  1. No.003:Longest Substring Without Repeating Characters

    问题: Given a string, find the length of the longest substring without repeating characters.Example:Gi ...

  2. ExecutorService常用方法和newFixedThreadPool创建固定大小的线程池

    1.ExecutorService: 是一个接口,继承了Executor: public interface ExecutorService extends Executor { } 2.Execut ...

  3. php面试题之一——PHP核心技术(高级部分)

    一.PHP核心技术 1.写出一个能创建多级目录的PHP函数(新浪网技术部) <?php /** * 创建多级目录 * @param $path string 要创建的目录 * @param $m ...

  4. Ansible用于网络设备管理 part 1 Jinja2 YAML初窥

    这一次的实验内容依然来自Kirk Byers的博客,源地址在https://pynet.twb-tech.com/blog/python/paramiko-ssh-part1.html 但是,这次实验 ...

  5. 初识Asp.net Identity

    第一篇,多多指教啦! 之前做asp.net的网站只知道Asp.net的身份验证方式有:Windows验证和Forms验证.今天初步了解了下asp.net的Identity技术,顺带了解了它之前的Mem ...

  6. 使用WCF对外提供接口

    本篇将通过WCF以webservices的方式对外提供接口.同时使用NUnit对webservices中的方法进行单元测试. 开发契约 contract Contract项目为类库项目,该项目下会包含 ...

  7. Force.com微信开发系列(三)申请测试账号及回复图文消息

    Force.com除了简单的文本消息回复外,还能回复图文并茂的消息.能回复音乐或者视频.能对用户发来的语音进行识别.能够搜集用户的地理位置信息并提供相应的内容或服务等,本文将对这些技能一一展开说明,在 ...

  8. java多线程系列8-线程的优先级

    在java中设置线程优先级使用setPriority,在jdk中的源代码如下: public final void setPriority(int newPriority) { ThreadGroup ...

  9. [转]一些NSArray,NSDictionary,NSSet相关的算法知识

    iOS编程当中的几个集合类:NSArray,NSDictionary,NSSet以及对应的Mutable版本,应该所有人都用过.只是简单使用的话,相信没人会用错,但要做到高效(时间复杂度)精确(业务准 ...

  10. Struts2(十一)OGNL标签三与Struts2标签

    一.UI标签 二.简单例子 <h1>添加信息</h1> <!--通过指定theme的属性改变主题 --> <s:form action="" ...