[NeetCode 150] Foreign Dictionary

Foreign Dictionary

There is a foreign language which uses the latin alphabet, but the order among letters is not “a”, “b”, “c” … “z” as in English.

You receive a list of non-empty strings words from the dictionary, where the words are sorted lexicographically based on the rules of this new language.

Derive the order of letters in this language. If the order is invalid, return an empty string. If there are multiple valid order of letters, return any of them.

A string a is lexicographically smaller than a string b if either of the following is true:

The first letter where they differ is smaller in a than in b.
There is no index i such that a[i] != b[i] and a.length < b.length.

Example 1:

Input: ["z","o"]

Output: "zo"

Explanation:
From “z” and “o”, we know ‘z’ < ‘o’, so return “zo”.

Example 2:

Input: ["hrn","hrf","er","enn","rfnn"]

Output: "hernf"

Explanation:

from “hrn” and “hrf”, we know ‘n’ < ‘f’
from “hrf” and “er”, we know ‘h’ < ‘e’
from “er” and “enn”, we know get ‘r’ < ‘n’
from “enn” and “rfnn” we know ‘e’<‘r’
so one possibile solution is “hernf”

Constraints:

The input words will contain characters only from lowercase ‘a’ to ‘z’.

1 <= words.length <= 100
1 <= words[i].length <= 100

Solution

From the order of the words, we can get the priority between 2 characters, which can be represented as a directed edge between them. When we organize all of the edges, we can get a DAG (Directed Acyclic Graph). Then we just need to do a topological sort with this DAG and get the answer.

Code

import queue

class Solution:
    def foreignDictionary(self, words: List[str]) -> str:
        edges = {c: set() for word in words for c in word}
        in_deg = {c: 0 for word in words for c in word}

        for i in range(len(words) - 1):
            w1, w2 = words[i], words[i + 1]
            minLen = min(len(w1), len(w2))
            if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:
                return ''
            for j in range(minLen):
                if w1[j] != w2[j]:
                    edges[w1[j]].add(w2[j])
                    break
        
        for value in edges.values():
            for c in value:
                in_deg[c] += 1

        print(edges)
        print(in_deg)

        que = queue.Queue()
        for key, value in in_deg.items():
            if value == 0:
                que.put(key)
        ans = []
        while not que.empty():
            cur = que.get()
            ans.append(cur)
            for nxt in edges.get(cur, []):
                in_deg[nxt] -= 1
                if in_deg[nxt] == 0:
                    que.put(nxt)
        print(ans)
        if len(ans) != len(in_deg):
            return ''
        return ''.join(ans)
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值