题解 | #火星文字典# 拓扑排序
火星文字典
https://www.nowcoder.com/practice/29d1622d47514670a85e98a1f47b8e2d
lst = input().split() # 入度表 in_degree = [-1 for i in range(26)] # 遍历Word_list中的每一个字母 # 出现过的字母入度变为0, -1就代表字母没出现过 for word in lst: for i in range(len(word)): in_degree[ord(word[i])-97] = 0 import collections graph = collections.defaultdict(list) for i in range(len(lst)-1): cur = lst[i] next = lst[i+1] n = len(cur) if len(cur) < len(next) else len(next) for j in range(n): # 如果不一样,就创建一条cur -> next 的有向边 if cur[j] != next[j]: in_degree[ord(next[j])-97] += 1 graph[cur[j]].append(next[j]) break queue = collections.deque() kind = 0 # 一共有多少种字符 for i in range(26): if in_degree[i] != -1: kind += 1 if in_degree[i] == 0: queue.appendleft(i) # 在弹出的时候 任何一次有两个入度为0的点就判为模棱两可 if len(queue) > 1: print('invalid') import sys sys.exit() ans = '' while queue: if len(queue) > 1: print('invalid') import sys sys.exit() cur = queue.pop() ans += chr(cur+97) for i in graph[chr(cur+97)]: in_degree[ord(i)-97] -= 1 if in_degree[ord(i)-97] == 0: queue.appendleft(ord(i)-97) print(ans if len(ans) == kind else 'invalid')