<Topological Sort> ( 高频, hard) 269
269. Alien Dictionary
这些就是有向图的边,对于有向图中的每个结点,计算其入度,然后从入度为0的结点开始 BFS 遍历这个有向图,然后将遍历路径保存下来返回即可。下面来看具体的做法:
根据之前讲解,需用 TreeSet 来保存这些 pair,我们还需要一个 HashSet 来保存所有出现过的字母,需要一个一维数组 in 来保存每个字母的入度,另外还要一个 queue 来辅助拓扑遍历,我们先遍历单词集,把所有字母先存入 HashSet,然后我们每两个相邻的单词比较,找出顺序 pair,然后我们根据这些 pair 来赋度,我们把 HashSet 中入度为0的字母都排入 queue 中,然后开始遍历,如果字母在 TreeSet 中存在,则将其 pair 中对应的字母的入度减1,若此时入度减为0了,则将对应的字母排入 queue 中并且加入结果 res 中,直到遍历完成。
最后看结果 sb 和 map.size() 中的元素个数是否相同,若不相同则说明可能有环存在,返回空字符串
Map<out, in>
class Solution {
public String alienOrder(String[] words) {
int[] indegree = new int[26];
Map<Character, Set<Character>> g = new HashMap<>();
buildGraph(g, words, indegree);
return bfs(g, indegree);
}
private void buildGraph(Map<Character, Set<Character>> g, String[] words, int[] indegree){
for(String word : words){
for(char c : word.toCharArray()){
g.putIfAbsent(c, new HashSet<>());
}
}
for(int i = 1; i < words.length; i++){
String first = words[i - 1];
String second = words[i];
int len = Math.min(first.length(), second.length());
for(int j = 0; j < len; j++){
if(first.charAt(j) != second.charAt(j)){
char out = first.charAt(j);
char in = second.charAt(j);
if(!g.get(out).contains(in)){
g.get(out).add(in);
indegree[in - 'a']++;
}
break;
}
}
}
}
private String bfs(Map<Character, Set<Character>> g, int[] indegree){
StringBuilder sb = new StringBuilder();
int totalChars = g.size();
Queue<Character> q = new LinkedList<>();
for(char c : g.keySet()){
if(indegree[c - 'a'] == 0){
sb.append(c);
q.offer(c);
}
}
while(!q.isEmpty()){
char out = q.poll();
if(g.get(out) == null || g.get(out).size() == 0) continue;
for(char in : g.get(out)){
indegree[in - 'a']--;
if(indegree[in - 'a'] == 0){
q.offer(in);
sb.append(in);
}
}
}
return sb.length() == totalChars ? sb.toString() : "";
}
}
269. Alien Dictionary
<Topological Sort> ( 高频, hard) 269的更多相关文章
- 【拓扑排序】【线段树】Gym - 101102K - Topological Sort
Consider a directed graph G of N nodes and all edges (u→v) such that u < v. It is clear that this ...
- topological sort~~~~初学
今天讲了topological sort 问题: 判环:记录入队的点数,若<n则有环,可证: 算法:o(n):queue or stack,而不是o(n^2)枚举 #. 关系运算图(vijos ...
- topological sort
A topological sortof a dag G is a linear ordering of all its vertices such that if G contains anedg ...
- 拓扑排序(Topological Sort)
Graph 拓扑排序(Topological Sort) 假设一个应用场景:你用 C 编写了一个爬虫工具,其中有很多自定义的库:queue.c.queue.h.stack.c.stack.h.heap ...
- Some facts about topological sort
Definition: a topological sort of a DAG G is a sort such that for all edge (i,j) in G, i precedes j. ...
- 6-16 Topological Sort(25 分)
Write a program to find the topological order in a digraph. Format of functions: bool TopSort( LGrap ...
- [Algorithms] Topological Sort
Topological sort is an important application of DFS in directed acyclic graphs (DAG). For each edge ...
- [MIT6.006] 14. Depth-First Search (DFS), Topological Sort 深度优先搜索,拓扑排序
一.深度优先搜索 它的定义是:递归探索图,必要时要回溯,同时避免重复. 关于深度优先搜索的伪代码如下: 左边DFS-Visit(V, Adj.s)是只实现visit所有连接某个特定点(例如s)的其他点 ...
- Leetcode: Alien Dictionary && Summary: Topological Sort
There is a new alien language which uses the latin alphabet. However, the order among letters are un ...
随机推荐
- Java实现抢红包功能
采用多线程模拟多人同时抢红包.服务端将玩家发出的红包保存在一个队列里,然后用Job定时将红包信息推送给玩家.每一批玩家的抢红包请求,其实操作的都是从队列中弹出的第一个红包元素,但当前的红包数量为空的时 ...
- 配置Postman通过OAuth 2 implicit grant获取Dynamics 365 CE Online实例的Access Token
微软动态CRM专家罗勇 ,回复335或者20190516可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 对于测试Web API, Get 类型,不需要设定特别reque ...
- Django 执行 makemigrations 显示 No changes detected in app
在Django项目配置一下多数据库,但是运行 makemigrations 执行不正常 $ python manage.py makemigrations polls No changes detec ...
- Java8_map新增方法
参考博客 https://irusist.github.io/2016/01/04/Java-8%E4%B9%8BMap%E6%96%B0%E5%A2%9E%E6%96%B9%E6%B3%95/#ge ...
- Appium使用总结
目前在使用appium过程中遇到的一些问题及规避方法总结如下: Appium使用总结:1.在熄屏下启动测试,会自动唤醒屏幕2.Appium只针对单个应用测试3.使用unittest框架,该框架中每条用 ...
- Python如何动态的为对象添加方法或属性,__slots__用法
代码示例如下: import types #使用MethodType方法需要导入包 class test(object): #定义 一个test类,包含name属性和f()方法 def __i ...
- 微信小程序的坑(持续更新中)
参与微信小程序开发有一段时间了,先后完成信息查询类和交易类的两个不同性质的小程序产品的开发:期间遇到各种各样的小程序开发的坑,有的是小程序基础功能不断改进完善而需要业务持续的适配,有的是小程序使用上的 ...
- swoole视频直播
$serv=new swoole_websocket_server("0.0.0.0",9501);$client=array();$serv->on("open& ...
- ch-0503
内容来源<算法竞赛进阶指南>date of submission:20191121tags:归排description modelling:你一定玩过八数码游戏,它实际上是在一个3*3的网 ...
- go语言之goto语句和函数和defer语句
1.goto关键字 import "fmt" func main() { for i := 0;i <11;i++{ if i == 2{ //关键字,goto跳转到某个位置 ...