Alien Dictionary

要点:topological sort,bfs

  • 只有前后两个word之间构成联系,一个word里的c是没有关系的
  • 只要得到两个word第一个不同char之间的partial order即可。topological sort就是把partial order变为total order

错误点:

  • ''.join(res)*(set(res)==chars)的含义:string*int,如果int是0那么实际返回的是''
  • defaultdict usage: umap[k] and umap[k]=0是不同的,前者不会强制set为0
  • don’t be too smart to compact everything: 比如可以开始建graph和indegree来保证所有char in (list comprehension can extend to dict comprehension)
  • zip新用法:相邻两两比较:构建pair: 注意zip不是等长的list,只返回有效部分。
  • 在构建graph的时候indegree[v]+=1对v已经在集合里的情况会重复++
# There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

# For example,
# Given the following words in dictionary, # [
# "wrt",
# "wrf",
# "er",
# "ett",
# "rftt"
# ]
# The correct order is: "wertf". # Note:
# You may assume all letters are in lowercase.
# If the order is invalid, return an empty string.
# There may be multiple valid order of letters, return any one of them is fine.
# Hide Company Tags Google Airbnb Facebook Twitter Snapchat Pocket Gems
# Hide Tags Graph Topological Sort
# Hide Similar Problems (M) Course Schedule II class Solution(object):
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
chars = set([c for word in words for c in word]) # error: inner loop at the end
graph, indegree = {c:set() for c in chars}, {c:0 for c in chars} for pair in zip(words, words[1:]): # note: zip if not even, ignore redundant
w1,w2 = pair[0],pair[1]
i = 0
while i<len(w1) and i<len(w2):
if w1[i]!=w2[i]:
graph[w1[i]].add(w2[i])
# indegree[w2[i]]+=1 # error case: w2[i] already in set, wrongly count twice
break
i+=1 for u in graph:
for v in graph[u]:
indegree[v]+=1 #print graph, indegree
q = [c for c in indegree if indegree[c]==0]
res = []
while q:
next = []
for c in q:
res.append(c)
for n in graph[c]:
indegree[n]-=1
if indegree[n]==0:
next.append(n)
q = next return ''.join(res)*(set(res)==chars) # error: don't forget cycle sol = Solution()
assert sol.alienOrder(["ab","adc"])=="acbd"
assert sol.alienOrder(["wrt","wrf","er","ett","rftt"])=="wertf"
assert sol.alienOrder(["za","zb","ca","cb"])=="azbc"
assert sol.alienOrder(["ri","xz","qxf","jhsguaw","dztqrbwbm","dhdqfb","jdv","fcgfsilnb","ooby"])==""

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

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

    Encode and Decode Strings 要点:题的特点:不是压缩,而是encode为字节流.所以需要找delimiter来分割每个word,但是delimiter可能是字符本身,所以可以用 ...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. ztree树 叶子节点路径的集合

    1.Question Description: ztree树各个节点都带有路径,如“/根节点”,"/根节点/一级节点",“根节点/一级节点/二级节点‘; 现在想获取所选的最末级节点 ...

  2. 线上mysql内存持续增长直至内存溢出被killed分析(已解决)

    来新公司前,领导就说了,线上生产环境Mysql库经常会发生日间内存爆掉被killed的情况,结果来到这第一天,第一件事就是要根据线上服务器配置优化配置,同时必须找出现在mysql内存持续增加爆掉的原因 ...

  3. javascript基础系列(入门前须知)

    -----------------------小历史---------------------------- javascript与java是两种语言,他们的创作公司不同,JavaScript当时是借 ...

  4. sqlserver 存储过程 try catch TRANSACTION (转)

    CREATE PROCEDURE YourProcedure    ASBEGIN    SET NOCOUNT ON; BEGIN TRY---------------------开始捕捉异常    ...

  5. JS中检测数据类型的四种方法

    1.typeof 用来检测数据类型的运算符->typeof value->返回值首先是一个字符串,其次里面包含了对应的数据类型,例如:"number"."st ...

  6. 【转】提高C#编程水平的50个要点

    1.总是用属性 (Property) 来代替可访问的数据成员2.在 readonly 和 const 之间,优先使用 readonly3.在 as 和 强制类型转换之间,优先使用 as 操作符4.使用 ...

  7. Static Cell-静态TableView

    使用静态TableView有两个前提,1.要在Storyboard上  2.需要使用TableViewController PS:如果需要设置不同的cell的高度不同的话,还是需要使用tableVie ...

  8. iOS支付宝集成详细流程

    实现支付宝支付的准备工作: 1.向支付宝签约,成为支付宝的商户 签约完成后,支付宝会提供一些必要的数据给我们 商户ID:partner 账号ID:seller 即支付宝账号 签约需要营业执照 2.获取 ...

  9. XMind快捷键

    XMind 是一款非常实用的思维导图软件,可以画各种结构图鱼骨图.二维图.树形图.逻辑图.组织结构图等!下面是常用的快捷键统计! 快捷鍵(Windows) 快捷鍵(Mac) 描述 Ctrl+N Com ...

  10. Hadoop从伪分布式到真正的分布式

    对这两天学习hadoop的一个总结,概念就不提了.直接说部署的事,关于如何部署hadoop网上的资料很多, 比较经典的还是Tim在IBM developworks上的系列文章 http://www.i ...