边工作边刷题: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 ...
随机推荐
- elasticsearch 之IK分词器安装
IK分词器地址:https://github.com/medcl/elasticsearch-analysis-ik 安装好ES之后就可以安装分词器插件了 记住选择ES对应的版本 对应的有版本选择下载 ...
- 常用jsp include用法,三种include的区别
<@ include file=””> :静态导入,jsp指令,同一个request , <jsp:include page=”” flush=””>:动作元素,不同一个req ...
- String系列
String 简介 String 是java中的字符串,它继承于CharSequence.String类所包含的API接口非常多.为了便于今后的使用,我对String的API进行了分类,并都给出的演示 ...
- spring jdbcTemplate query
1. spring jdbcTemplate query需要实现mapRow方法 package com.cdv.apolloagent.jdbc.dao.impl; import java.sql. ...
- 【洛谷 p3368】模板-树状数组 2(数据结构)
题目:已知一个数列,你需要进行下面两种操作:1.将某区间每一个数数加上x:2.求出某一个数的和. 解法:树状数组+前缀和优化.数组中每位存和前一位的数的差,这样区间修改只用改两位,单点询问就是求前缀和 ...
- ahjesus js 快速求幂
/* 快速幂计算,传统计算方式如果幂次是100就要循环100遍求值 快速幂计算只需要循环7次即可 求x的y次方 x^y可以做如下分解 把y转换为2进制,设第n位的值为i,计算第n位的权为x^(2^(n ...
- D/A转换器
电荷:带正负电的基本粒子.电的本质是使正负电荷分开,使电荷发生移动,实质是电子的转移,并不是创造电荷.电压:单位正电荷受电场力作用从A点移动到B点所做的功.电压方向从高电位指向低点位.电压是推动电荷定 ...
- Android studio 快捷添加构造方法以及set与get
第一种方式 快捷键: Alt + lnsert (笔记本可能没有后面的按键) 按快捷键会出现下面这个页面: 第二种方式:点开后是跳出上面那个选择框
- SET UPDATE TASK LOCAL
SET Effect Switches on the local update task. This means that when you specify CALL FUNCTION ... IN ...
- 移动,企业社交(sharepoint2013)--jindahao(金大昊)
MobileIncreasingly, a major component of sharing and collaborating involves mobile access. SharePoin ...