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. NYOJ:题目860 又见01背包

    题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=860 方法一:不用滚动数组(方法二为用滚动数组,为方法一的简化) 动态规划分析:最少要拿总 ...

  2. mvc与三层结构终极区别

    http://blog.csdn.net/csh624366188/article/details/7183872 http://www.cnblogs.com/zhhh/archive/2011/0 ...

  3. [ASP.NET MVC] 使用Bootsnipp样式

    [ASP.NET MVC] 使用Bootsnipp样式 前言 在「[ASP.NET MVC] 使用Bootstrap套件」这篇文章中,介绍了如何在Web项目里使用Bootstrap套件,让用户界面更加 ...

  4. andriod ==和equals

    == 用于数字 equals用于字符

  5. maven eclipse 插件下载地址

    要用的时候,搜索了半天,自己记录下 单独下载地址 http://maven.apache.org/download.cgi eclipse 更新地址 http://download.eclipse.o ...

  6. 【读书笔记】iOS-AppKit简介

    一,IBOutlet和IBAction.它们实际上只是AppKit提供的#defines.IBOutlet的含义没有任何作用,因此将不对对它时行编译.IBAction定义为void,这意味着在AppC ...

  7. iOS网络-03-NSURLSession与NSURLSessionTask

    简介 NSURLSession也能完成网络请求 NSURLConnection在iOS9中不推荐使用,NSURLSession是iOS9中推荐使用的网络请求方式 NSURLSession需要与NSUR ...

  8. System.Data.Entity 无法引用的问题

    最近刚学MVC,跟着网上的博客学习,发现代码中有这样一句: using System.Data; using System.Data.Entity; 我项目引用的时候,也引用了System.Data. ...

  9. chrome和搜狗浏览器的js问题

    1.在chrome中如果是js添加颜色必须用"#00CC00",必须加#号...不然会出问题,但是在搜狗浏览器中可以没有#号也能正确识别...

  10. 你所不知道的SQL Server数据库启动过程(用户数据库加载过程的疑难杂症)

    前言 本篇主要是上一篇文章的补充篇,上一篇我们介绍了SQL Server服务启动过程所遇到的一些问题和解决方法,可点击查看,我们此篇主要介绍的是SQL Server启动过程中关于用户数据库加载的流程, ...