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:
Given the following words in dictionary,
The correct order is: “wertf”.
Example 2:
Given the following words in dictionary,
The correct order is: “zx”.
Example 3:
Given the following words in dictionary,
The order is invalid, so return “”.
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.
解法1: Topological sort
此题的难点是看出来这是一题graph。
本质上这题的意思是不同的字符之间有顺序,而我们要找出来这个隐藏的顺序。
那么graph的node就是可能的字符,用一个26大小的array记录每一个字符的入度和出度。
然后遍历相邻的两个string,搜索直到两个字符不一样为止,然后用一个adjacent matrix记录两者之间的关系
同时增加后一个字符的入度。
等完成了之后只需要用一个queue做一个topological sort就可以了。
|
|