classSolution(object): defalienOrder(self, words): """ :type words: List[str] :rtype: str """ if words isNoneor words == []: return"" chars = set().union(*map(set, words)) outs = {c : set() for c in chars} indegrees = {c : 0for c in chars} for i in range(len(words) - 1): before, after = words[i], words[i + 1] for j in range(min(len(before), len(after))): if before[j] != after[j]: if after[j] notin outs[before[j]]: indegrees[after[j]] += 1 outs[before[j]].add(after[j]) break
q = [k for k, v in indegrees.items() if v == 0] soln = [] while q: curr_char = q.pop() soln.append(curr_char) for next_char in outs[curr_char]: indegrees[next_char] -= 1 if indegrees[next_char] == 0: q.append(next_char)
if max(indegrees.values()) > 0: return"" else: return"".join(soln)