Alien Dictionary
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 non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
Example
Example 1:
Example 2:
Example 3:
Note:
You may assume all letters are in lowercase.
You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
Note
"wrt",
"wrf", t -> f
"er", w -> e
"ett", r -> t
"rftt" e -> r
建图:前一个字符串和后一个字符串比较不同的地方,之前的是key,所以之后的set是value(其degree加一)
对这个图进行topo排序
注:可能有多个解的,这里没有给出正常顺序的最小序列,否则得用heapq来做拓扑排序
Code
Last updated