每天两道LeetCodeHard:(38)

379 阅读1分钟

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.

解释:

给一个字符数组,找其中蕴藏的字母之间的顺序

思考:

拓扑排序的本质是从一堆相对关系中找绝对关系。因此我们要做的其实就是从字符串中得到临街表,然后统计入度,最后按照拓扑排序过程一步一步的去除即可。至于单词的解析,只需要知道每一对单词只有第一个不同的字符能得出关系即可。

答案:

from collections import deque
class Solution:
    def alienOrder(self, words) -> str:
        nextMap = [[0]*26 for i in range(26)]
        indegree = [0]*26
        charSet =set()
        charSetAll = set()
        res=[]
        for i in range(len(words)-1):
            first = words[i]
            second = words[i+1]
            for i in range(min(len(first),len(second))):
                if first[i] == second[i]:
                    charSetAll.add(ord(first[i])-ord('a'))
                    continue
                else:
                    index1 = ord(first[i])-ord('a')
                    index2 = ord(second[i])-ord('a')
                    charSet.add(index1)
                    charSet.add(index2)
                    nextMap[index1][index2]=1
                    indegree[index2]+=1
                    break
        q =deque()
        for i in range(26):
            if i in charSet and indegree[i] ==0:
                q.append(i)
                break
        while q:
            i = q.popleft()
            res.append(chr(i+ord('a')))
            for j in range(26):
                if nextMap[i][j]==1:
                    indegree[j]-=1
                    if indegree[j]==0:
                        q.append(j)
        for i in charSetAll-charSet:
            res.append(chr(i+ord('a')))  
        return "".join(res)           
def main():
    sol = Solution()
    print(sol.alienOrder(['z','z']))
main()

答案补充: