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. NLog在.NET Core Console Apps中的简单应用

    什么是NLog? NLog is a free logging platform for .NET with rich log routing and management capabilities. ...

  2. 布局文件预览:Rendering Problems Exception raised during rendering: Unable to find the layout for Action Bar.的解决

    在android studio或者eclipse中打开layout文件,发现不能预览布局,提示以下错误: Rendering Problems Exception raised during rend ...

  3. YUIDoc example代码高亮错误、生成API文档目录不按源文件注释顺序

    1.如果发现yuidoc命令用不了,那就重装nodejs吧 昨天不知道是清扫电脑的原因,yuidoc命令用不了(命令不存在),也没有找到好的解决方法,怒重装YUIDoc也不行.最后想了想,怒重装了no ...

  4. [ html canvas globalCompositeOperation ] canvas绘图属性 设置合成图像如何显示 属性演示

    <!DOCTYPE html> <html lang='zh-cn'> <head> <title>Insert you title</title ...

  5. How to copy files between sites using JavaScript REST in Office365 / SharePoint 2013

    http://techmikael.blogspot.in/2013/07/how-to-copy-files-between-sites-using.html I'm currently playi ...

  6. Force.com微信开发系列(二)用户消息处理

    Force.com是国际知名的云平台公司,成功配置好Force.com作为微信公开号的服务端后,接下来需要的任务是处理用户发送的消息.当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML ...

  7. 读书笔记2014第6本:《The Hunger Games》

    以前从未读过一本完整的英文小说,所有就在今年的读书目标中增加了一本英文小说,但在头四个月内一直没有下定决定读哪一本.一次偶然从SUN的QQ空间中看到Mockingjay,说是不错的英文小说,好像已经是 ...

  8. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q100-Q103)

    Question 100You create a Web Part.You need to display the number of visits to a SharePoint site coll ...

  9. iOS菜单滚动联动内容区域功能实现

    平时开发APP中关于此功能还是比较经常碰到,本实例借用三个开源的插件,并对其中一个进行修改调整实现出想要的效果:本文重点介绍修改的内容跟三个插件的运用,这三个插件还可以各自扩展到其它项目的运用: 效果 ...

  10. Android WebView 向上向下滑动监听

    在手势的 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,   float velocityY) {}代码 ...