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. DP入门---Robberies

    HDU  2955 Description The aspiring Roy the Robber has seen a lot of American movies, and knows that ...

  2. 【Asphyre引擎】关于AsphyreTypes中OverlapRect的改动,都是泪啊!!!

    OverlapRect改动:两个参数对调了.想问问LP,这样真的好吗? Sphinx304版本的代码: function OverlapRect(const Rect1, Rect2: TRect): ...

  3. IT外包行业与职业发展

          在IT行业,总是有一些IT外包公司的存在,凡是存在的都是合理的.当你做为IT从业人员应该尽量避免去外包公司工作 .特别是你从事软件开发工作.     先来说说缘由,一些外包公司本来是从事软 ...

  4. 如何选择RabbitMQ的消息保存方式?

    RabbitMQ对于queue中的message的保存方式有两种方式:disc和ram.如果采用disc,则需要对exchange/queue/delivery mode都要设置成durable模式. ...

  5. 【GOF23设计模式】享元模式

    来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_享元模式.享元池.内部状态.外部状态.线程池.连接池 package com.test.flyweight; /** * ...

  6. all things are difficult before they are easy

    刚开始接触一项新知识时,总是感觉很难,只要你用心钻研下去,它会慢慢变简单的.

  7. NSMutable sort排序

    Compare method Either you implement a compare-method for your object: - (NSComparisonResult)compare: ...

  8. IntelliJ IDEA 2016.2.4下载与注册码

    下载地址 https://download.jetbrains.8686c.com/idea/ideaIU-2016.2.4.dmg 注册码 43B4A73YYJ-eyJsaWNlbnNlSWQiOi ...

  9. sqlite数据库 select 查询带换行符数据

    在sqlite 数据库中用 select 语句查询带 换行符的 数据信息 实现 SELECT   * from questions_exec where title like     '%'||x'0 ...

  10. Android 开发之Windows环境下Android Studio安装和使用教程(图文详细步骤)

    鉴于谷歌最新推出的Android Studio备受开发者的推崇,所以也跟着体验一下. 一.介绍Android Studio  Android Studio 是一个Android开发环境,基于Intel ...