边工作边刷题:70天一遍leetcode: day 81-1
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的更多相关文章
- 边工作边刷题:70天一遍leetcode: day 81
Encode and Decode Strings 要点:题的特点:不是压缩,而是encode为字节流.所以需要找delimiter来分割每个word,但是delimiter可能是字符本身,所以可以用 ...
- 边工作边刷题:70天一遍leetcode: day 89
Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...
- 边工作边刷题:70天一遍leetcode: day 77
Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...
- 边工作边刷题:70天一遍leetcode: day 78
Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...
- 边工作边刷题:70天一遍leetcode: day 85-3
Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...
- 边工作边刷题:70天一遍leetcode: day 101
dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...
- 边工作边刷题:70天一遍leetcode: day 1
(今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...
- 边工作边刷题:70天一遍leetcode: day 70
Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...
- 边工作边刷题:70天一遍leetcode: day 71-3
Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...
- 边工作边刷题:70天一遍leetcode: day 71-2
One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...
随机推荐
- lnmp+phpmyadmin配置与出现问题
本博客归moka同学(新浪微博:moka同学)本人亲自整理,如有使用,请加链接注明出处. lnmp 安装完全后,配置phpmyadmin .其访问方式为 http://202.18.400.379/p ...
- transfer between javabean and map
1. java bean 转化成 map import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.P ...
- 【iOS】Quartz2D信纸条纹
一.前导程序 新建一个项目,在主控制器文件中实现以下几行代码,就能轻松的完成图片在视图中的平铺. - (void)viewDidLoad { [super viewDidLoad]; UIImage ...
- .NET Core添加项目之间的依赖关系
- j2ee分布式缓存同步实现方案dlcache v1.0.0
现成的分布式K/V缓存已经有很多的实现,最主要的比如redis,memcached,couchbase.那为什么我们还要自己去实现呢,在我们解决了分布式系统下大量rpc调用导致的高延时后,我们发现很多 ...
- hdu 1518 拼正方形
本题来自:http://acm.hdu.edu.cn/showproblem.php?pid=1518 题意:输入几个长度,判断能否拼成正方形. 以下部分参考了网友代码,终于ac啦. #include ...
- UIMenuController的使用
1, 基本使用 以对一个UILabel长按弹出菜单为例 子类化UILabel 因为需要覆盖这几个方法:- (BOOL)canBecomeFirstResponder; 返回YES 同时需要在每次UI元 ...
- KindEditor编辑器在ASP.NET中的使用
KindEditor编辑器在ASP.NET中的使用 最近做的项目中都有用到富文本编辑器,一直在寻找最后用的富文本编辑器,之前用过CKEditor,也用过UEditor,这次打算用 一下KindEdit ...
- GetStartedWithWin10Develop
GetStartedWithWin10Develop 首先要确保已经配置好win10开发环境,开始第一个win10开发的HelloWorld 1.首先创建你的win10项目(示例的项目名称为 Hell ...
- web api 限制单个IP在一定时间内访问次数
ps:下面实例是每隔30秒访问次数不超过3次 1.Filter: using Infrastructure.Log; using Infrastructure.Web; using Lemon.Sta ...