Alien Dictionary

update Sep 6 2018, 0:36

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 1:

Input:
[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]

Output: "wertf"

Example 2:

Input:
[
  "z",
  "x"
]

Output: "zx"

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.

Basic Idea:

输入为一串按照字典顺序排序的字符串,要求根据给定顺序,输入一个符合条件的字符字典顺序序列,有可能不存在符合要求的顺序。

我们可以将这个问题抽象为图的问题,每个字符可以视为一个 GraphNode,每两个给定字符串之间的相互顺序可以抽象为图的边,例如 abc, abe 则可以推得一条边:c->e。之后我们可以利用这种关系生成 Graph,对所有的 node 进行topological sort,这样就可以求得解。需要注意,如果没有valid解,体现为图中有环, sort的时候检查环即可。检查的方法为如果当queue为空后,res.size() != graph.size(),则说明有环。

Java Code:

Update: Without Node class

之前的实现没有考虑重复边的问题,导致可能会有同样的边被多次加入,这样会增加时间复杂度。另外,其实也可以不另外定义Node class,可以用一个 Map<Character, Set<Character> 和一个 int[] indegrees 来表示graph和indegree map。

Java Code: