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. mysql awr v1.0.1发布

    现发布mysql awr v1.0.1 修复问题: 1.galera cluster下flush table/index_statistcs时如果系统中业务ddl频繁可能会导致很多进程处于prepar ...

  2. 每一个成功的程序员的身后都有一个--------Parse

    相信好多同行都用过Parse,而正是因为Parse给我们的开发带来的极大的便利,才有了项目从零开始,到正式上线仅仅用上不到两周的时间,现在Swift还在迅速的发展,很快就会占有大量的市场,现在就就结合 ...

  3. 高性能文件缓存key-value存储—Memcached

    1.高性能文件缓存key-value存储—Redis 2.ASP.NET HttpRuntime.Cache缓存类使用总结 备注:三篇博文结合阅读,简单理解并且使用,如果想深入学习,请多参考文章中给出 ...

  4. jquery动态创建节点

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. DOJO官方API翻译或解读-dojo/_base/lang --hitch()

    hitch() hitch() 是一个函数,会在给定的上下中执行给定一个执行函数.hitch允许你去控制一个函数如何执行,往往在异步操作中起作用. 我们常常会写出这样的代码:(博主:这个代码意图在&q ...

  6. 复制转移sharepoint 2010 designer做的list workflow的方法

    SharePoint 2010 designer做的workflow都有一个导出到visio的功能,但是如果是list workflow一般都是不可重用的,即使导出了,也是导不进目标站点或者list的 ...

  7. UIViewController的edgesForExtendedLayout属性

    UIViewController的edgesForExtendedLayout属性 想必大家都遇到一种情况,明明y坐标设置的是0,但是总是被讨厌的导航栏给遮住.比如下面这个情况: UILabel *l ...

  8. iOS开发之网络编程--1、NSURLSession的基本使用

    前言:学习NSURLSession的使用之前,先学习一篇关于NSURLSession的好文章<From NSURLConnection to NSURLSession>或者是国内的译文&l ...

  9. UVa 109 - SCUD Busters(凸包计算)

    题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&pa ...

  10. nginx 与 lua 开发环境搭建

    首先下载最新版的 相关软件 的安装文件. nginx: http://nginx.org/en/download.html LuaJIT: http://luajit.org/download.htm ...