leetcode-269-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 1:
1 | Input: |
Example 2:
1 | Input: |
Example 3:
1 | Input: |
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.
分析
输入的一系列word,连续的俩俩 word 之间可以确定两个字符之间的先后顺序,或者无法确定得出任意两个字符之间的顺序(前一个字符是后一个字符的前缀的情况下)。因此我们可以使用拓扑排序得到一个符合要求的顺序。另外要注意在所有 word 出现过的字符都要给出在答案中出现,所以先对所有字符遍历一遍将其入度都设置为1表示该字符的存在。
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/12/leetcode-269/
License: 知识共享署名-非商业性使用 4.0 国际许可协议