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:

Input:
[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]

Output: "wertf"

Example 2:

Input:
[
  "z",
  "x"
]

Output: "zx"

Example 3:

Input:
[
  "z",
  "x",
  "z"
] 

Output: "" 

Explanation: The order is invalid, so return "".

Note:

  • You may assume all letters are in lowercase.
  • 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. 字典序的信息是首個不相同字母,剛開始居然字符串內部挖掘邊的關係

2. codes裏標bug的地方

from collections import defaultdict

class Solution:
    def alienOrder(self, words) -> str:
        nxt_edges, in_degree = defaultdict(set), defaultdict(int)
        lw = len(words)
        if (lw == 0):
            return ""

        pre,res = "",""
        for cur in words:
            for ch in cur:
                in_degree[ch] = in_degree[ch]
            if (pre.startswith(cur) and len(pre)>len(cur)):
                return "" #bug2 could not find in description
            for pre_ch, cur_ch in zip(pre, cur):
                if (pre_ch != cur_ch):
                    if (cur_ch not in nxt_edges[pre_ch]): #bug1: if (pre_ch != cur_ch and cur_ch not in nxt_edges[pre_ch])
                        nxt_edges[pre_ch].add(cur_ch)
                        in_degree[cur_ch] += 1
                    break
            pre = cur

        in_degree_0 = [k for k, v in in_degree.items() if v == 0]
        while (in_degree_0):
            cur = in_degree_0.pop()
            res += cur
            for nxt in nxt_edges[cur]:
                in_degree[nxt] -= 1
                if (in_degree[nxt] == 0):
                    in_degree_0.append(nxt)

        return res if (len(res) == len(in_degree)) else ""

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章